Skip to the solution
MediumFrontend5 min read

How do you handle redirects and rewrites in Next.js?

813 views

The problem

Question presented to candidate: "Explain the difference between a redirect and a rewrite, and all the places in Next.js where you can do each one."

What a strong answer should cover:

  • A redirect answers with a 3xx status and a Location header, so the browser requests the new URL and the address bar changes.
  • A rewrite serves the content of another path (or another server) while the URL stays the same.
  • In next.config: redirects() (permanent gives 308, otherwise 307), rewrites() with beforeFiles, afterFiles and fallback phases, and headers().
  • In code: redirect() and permanentRedirect() in Server Components and Server Actions, and NextResponse.redirect or rewrite in Proxy.
  • Rules can match on paths, wildcards, headers, cookies and query strings with has and missing.

Clarifying questions expected:

  • "Is the move permanent?" β€” permanent redirects are cached by browsers and pass SEO signals.
  • "Does the decision depend on the request (cookie, locale)?" β€” then Proxy or code, not static config.

Code / implementation expected: Yes β€” config rules and a redirect in code.

  • nextjs
  • redirects
  • rewrites
  • middleware

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read Β· 8 sections

Read the code

Config rules and a redirect in code
// next.config.ts
const nextConfig = {
  async redirects() {
    return [
      { source: "/old-blog/:slug", destination: "/blog/:slug", permanent: true },           // 308
      { source: "/beta", destination: "/", permanent: false, missing: [{ type: "cookie", key: "beta" }] },
    ];
  },
  async rewrites() {
    return {
      beforeFiles: [{ source: "/about-us", destination: "/about" }],
      afterFiles: [{ source: "/api/legacy/:path*", destination: "https://legacy.example.com/:path*" }],
      fallback: [],
    };
  },
};
export default nextConfig;

// app/checkout/actions.ts
"use server";
import { redirect } from "next/navigation";
export async function placeOrder(formData: FormData) {
  const order = await createOrder(formData);
  redirect(`/orders/${order.id}`); // after the mutation
}

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 48 of 129 in Next.js

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Next.js questions
Up nextMedium

How do View Transitions work with next/link transitionTypes in Next.js 16.2?

Continue