Redirects and rewrites

Intermediate · 6 min

redirect(), permanentRedirect, next.config redirects and rewrites, and proxy.ts. Which one to use, which status codes they send, and how a rewrite differs.

Before thisLinking and moving between pages

Codevolution · 6 min

Redirects and rewrites

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A redirect tells the browser to go to a different URL; a rewrite serves a different page's content while the address bar keeps the original URL.
  • Next.js has four ways to redirect: `redirect()` and `permanentRedirect()` during rendering, `redirects` in `next.config`, and `NextResponse.redirect` in `proxy.ts` for conditional logic.
  • Known, fixed path changes belong in `next.config`; decisions that depend on cookies, headers or other request data belong in `proxy.ts`.
  • `redirect()` works by throwing, so call it outside any `try` block; in Next.js 16 `middleware.ts` is renamed `proxy.ts`.

Two different promises

A redirect says “that moved; go here.” The server answers with a 3xx status and a Location header, the browser makes a second request, and the address bar changes. A rewrite says “serve this other thing, but do not tell the visitor.” The server fetches content from a different path internally and responds under the original URL. Redirects are for pages that moved or actions that finished. Rewrites are for hiding structure: /docs/* can be served from another host without the visitor leaving your domain.

Four ways to redirect

The Next.js docs lay these out in one table.

API Use it for Where Status
redirect After a mutation or event Server Components, Server Functions, Route Handlers 307, or 303 from a Server Action
permanentRedirect A canonical URL changed for good Same 308
redirects in config Known path-to-path moves next.config.ts 307 or 308
NextResponse.redirect Conditional on the request proxy.ts Any

Client Components use useRouter().push from an event handler, as covered in linking and moving between pages.

During render: redirect()

import { redirect } from "next/navigation";

export default async function Page({ params }: PageProps<"/posts/[id]">) {
  const { id } = await params;
  const post = await getPost(id);
  if (!post) redirect("/posts");
  return <h1>{post.title}</h1>;
}

redirect throws a special error to unwind the render, so TypeScript knows nothing after it runs. The consequence: never wrap it in try/catch, or your catch will swallow it. Call it outside the try. In a Server Action, redirect performs a client-side navigation when JavaScript is available and a 303 otherwise. permanentRedirect is the same with 308, for when a canonical URL changes, such as a username change.

In config: fixed moves

When the old and new paths are known ahead of time, declare them:

// next.config.ts
const nextConfig: NextConfig = {
  async redirects() {
    return [
      { source: "/old-blog/:slug", destination: "/blog/:slug", permanent: true },
    ];
  },
  async rewrites() {
    return [
      { source: "/docs/:path*", destination: "https://example.com/docs/:path*" },
    ];
  },
};

permanent: true sends 308, false sends 307. These run before rendering and support path parameters, plus header, cookie and query matching. I confirmed on a built scratch app that /old-blog/hello answered 308 with Location: /blog/hello. The rewrite example proxies /docs/* to another origin while the address bar stays on your domain.

In the proxy: decisions per request

When the choice depends on who is asking, use proxy.ts at the project root:

// proxy.ts
import { NextResponse, type NextRequest } from "next/server";

export function proxy(request: NextRequest) {
  if (request.nextUrl.pathname === "/old-about") {
    return NextResponse.redirect(new URL("/about", request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: "/old-about" };

A request to /old-about on the built scratch app answered 307 with Location: /about. The same file can rewrite (NextResponse.rewrite), set cookies and headers, or short-circuit with a response. Always set a matcher so it only runs where needed. In Next.js 16, middleware.ts was deprecated and renamed proxy.ts, and the exported function is proxy; an automatic codemod does the rename. The proxy gets its own lesson later, in the proxy file.

Choosing

Fixed moves between known paths go in next.config, because they are declarative and cheap. Anything depending on cookies or auth goes in the proxy. Anything that is a consequence of a mutation or a missing record goes in redirect().

What the video covers

Codevolution’s chapters cover setting up middleware, redirection, conditional statements, URL rewrites with middleware, and handling cookies and headers. It teaches the middleware version of this lesson: the file is named middleware.ts and exports middleware, which Next.js 16 renamed to proxy.ts and proxy, so apply the rename when you follow it. The redirects and rewrites config keys and the redirect() function are not in the video; this lesson carries them. The runner-up is a short video on the new proxy file in Next.js 16 from a small channel, and I have not been able to verify its content beyond its title.

Where this fits

This closes the routing group. Next, server components in Next.js starts the group on where code runs.

Check yourself

  1. 01How is a rewrite different from a redirect?

    A redirect sends the browser an HTTP response telling it to request a new URL, so the address bar changes. A rewrite fetches the content of a different path on the server and returns it under the original URL, so the visitor never sees the change.

  2. 02Why should `redirect()` not be called inside a `try` block?

    `redirect()` works by throwing a special error that Next.js catches to perform the redirect. A `catch` block in your own code would swallow it and the redirect would never happen.

  3. 03When would you choose `proxy.ts` over `redirects` in `next.config`?

    When the decision depends on the request itself, such as a cookie, a header, or an authentication state. `next.config` redirects are matched by path, header, cookie and query patterns declared ahead of time, while a proxy can run arbitrary logic per request.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark