Day 20 โ Redirects: Sending Users Away
๐งญ Day 20 โ Redirects: Sending Users Away
Zero to Hero โ Hands-on Next.js Tutorial
Weโve moved users with <Link> (Client) and NextResponse.redirect (Middleware).
But what if you are deep inside a Server Component or Server Action and need to move the user?
๐ฆ 1. The redirect() function
Import it from next/navigation. It works in Server Components, Client Components, Route Handlers, and Server Actions.
How it works:
It throws a special error NEXT_REDIRECT that interrupts rendering and tells the router to move.
import { redirect } from 'next/navigation';
export default async function Page({ params }) {
const team = await fetchTeam(params.id);
if (!team) {
redirect('/404'); // Bails out here immediately
}
// This code never runs if redirected
return <h1>{team.name}</h1>;
}
- Default: Returns 307 (Temporary Redirect).
- Permanent:
redirect('/new', RedirectType.push).
๐ฉ 2. permanentRedirect()
If you are changing your URL structure permanently (SEO impact), use this. It returns a 308 status code, telling Google to update its index.
import { permanentRedirect } from 'next/navigation';
export async function oldProfilePage() {
permanentRedirect('/profile/new-me');
}
๐ง 3. next.config.js Redirects
For static, well-known redirects (e.g., /discord -> discord.gg/...), configure them in next.config.js. This is slightly faster as it happens before the app loads.
module.exports = {
async redirects() {
return [
{
source: '/discord',
destination: 'https://discord.gg/my-server',
permanent: true,
},
{
source: '/old-blog/:slug',
destination: '/blog/:slug', // Matches params!
permanent: true,
},
]
},
}
๐งช Challenge: Day 20
- Create a page
/admin. - Inside the component, just write
redirect('/'). - Visit
/admin. You should be instantly bounced back to Home. - Try putting a
console.logafter the redirect. It should never print.
See you tomorrow for Parallel Routes (The dashboard killer feature)! ๐๏ธ