#nextjs #redirects #routing #navigation

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

  1. Create a page /admin.
  2. Inside the component, just write redirect('/').
  3. Visit /admin. You should be instantly bounced back to Home.
  4. Try putting a console.log after the redirect. It should never print.

See you tomorrow for Parallel Routes (The dashboard killer feature)! ๐Ÿ—๏ธ