Skip to main content

Web frameworks · Intermediate · 24 min

Redirect and rewrite requests with proxy.ts in Next.js 16

By Padding · Updated 18 Nov 2026
Node.js 26 (node:26 image) · Next.js 16.4.6 · React 19.3

You will write a Next.js 16 proxy.ts that redirects old URLs from a map, rewrites one path to another route, adds a request header, picks a language from Accept-Language and sends signed-out visitors to a login page, then prove the redirect map with a curl script against a production build.

On this page

Next.js 16 renamed middleware.ts to proxy.ts, and the exported function from middleware to proxy. The code inside works the same way. The new name says what the file really is: a small piece of code that stands in front of your app, sees each request first, and decides whether to let it through, send it somewhere else, or change it on the way. It runs before any page or route handler, on the Node.js runtime by default.

That position makes it good at a short list of jobs, and bad at almost everything else. Good: redirecting old URLs, serving one route under another path, adding headers, choosing a language, and turning away visitors who are plainly signed out. Bad: anything slow, such as a database query, and anything that has to be correct for security, such as deciding whether a user may see a record. Those checks belong next to the data.

You will build a small site with English, French and Swahili home pages, versioned docs and an account page, and give it one proxy.ts that does all five jobs. Each job gets its own curl check. At the end you run a script that checks a whole redirect map against a production build, the kind of test you can keep in CI when you move URLs around.

Step 1 · Create the project and find where proxy.ts goes

Create a Next.js 16.4.6 project in a throwaway folder. The options match the App Router tutorial, including a src/ folder:

Bash
cd ~
npx create-next-app@16.4.6 proxy-demo --ts --tailwind --eslint --app --src-dir --use-npm --import-alias "@/*" --disable-git --yes
cd ~/proxy-demo

There is one proxy file per project. It sits at the same level as the app folder: in the project root for a project without src/, and at src/proxy.ts for this one. A proxy.ts in the wrong place is ignored without an error, which is the most common reason a proxy "does nothing".

If you are upgrading an older project that has middleware.ts, the Next.js codemod renames the file and the function for you. middleware.ts still runs in Next.js 16, but it is deprecated. Run the codemod from that project's root, not in this demo:

Bash
npx @next/codemod@canary middleware-to-proxy .

Check it worked

create-next-app ends with Success! Created proxy-demo. Confirm that the app folder is inside src, which tells you where the proxy file will go:

Bash
cd ~/proxy-demo
ls src
grep '"next"' package.json

The first command prints app. The second prints a line with "next": "16.4.6".

Step 2 · Add the pages the proxy will route to

The proxy needs somewhere to send people. Replace the starter layout with a plain one that links to the three areas, and remove the starter home page, because the proxy will answer / itself:

Bash
cd ~/proxy-demo
rm src/app/page.tsx
cat > src/app/layout.tsx <<'TSX'
import type { Metadata } from "next";
import Link from "next/link";
import "./globals.css";

export const metadata: Metadata = { title: "Proxy demo" };

export default function RootLayout({ children }: LayoutProps<"/">) {
  return (
    <html lang="en">
      <body className="mx-auto max-w-2xl p-6">
        <nav className="flex gap-4 pb-6">
          <Link href="/en">Home</Link>
          <Link href="/docs/latest/install">Docs</Link>
          <Link href="/account">Account</Link>
        </nav>
        {children}
      </body>
    </html>
  );
}
TSX

The supported languages live in one module, so the pages and the proxy agree on them. The pickLocale function reads an Accept-Language header, which every browser sends, and ranks its entries by their q weight. A header such as sw-KE,sw;q=0.9,en;q=0.8 means Swahili as spoken in Kenya first, any Swahili next, then English:

Bash
cd ~/proxy-demo
mkdir -p src/lib
cat > src/lib/locale.ts <<'TS'
export const locales = ["en", "fr", "sw"] as const;
export type Locale = (typeof locales)[number];
export const defaultLocale: Locale = "en";

export function isLocale(value: string | undefined): value is Locale {
  return value !== undefined && (locales as readonly string[]).includes(value);
}

// "sw-KE,sw;q=0.9,en;q=0.8" -> "sw". Unknown or missing -> "en".
export function pickLocale(header: string | null): Locale {
  if (!header) return defaultLocale;
  const ranked = header
    .split(",")
    .map((part) => {
      const [tag, ...params] = part.trim().split(";");
      const q = params.map((p) => p.trim()).find((p) => p.startsWith("q="));
      return {
        lang: tag.trim().toLowerCase().split("-")[0],
        weight: q ? Number(q.slice(2)) : 1,
      };
    })
    .filter((entry) => entry.lang && entry.weight > 0)
    .sort((a, b) => b.weight - a.weight);
  for (const { lang } of ranked) {
    if (isLocale(lang)) return lang;
  }
  return defaultLocale;
}
TS

Now one home page per language, under a [lang] segment, and version 2 of the docs at /docs/v2/<topic>. Both list their values in generateStaticParams, so they are built ahead of time:

Bash
cd ~/proxy-demo
mkdir -p "src/app/[lang]" "src/app/docs/v2/[topic]"
cat > "src/app/[lang]/page.tsx" <<'TSX'
import Link from "next/link";
import { notFound } from "next/navigation";
import { isLocale, locales } from "@/lib/locale";

const text = {
  en: { title: "Welcome", body: "Start with the install guide." },
  fr: { title: "Bienvenue", body: "Commencez par le guide d'installation." },
  sw: { title: "Karibu", body: "Anza na mwongozo wa usakinishaji." },
};

export function generateStaticParams() {
  return locales.map((lang) => ({ lang }));
}

export default async function HomePage({ params }: PageProps<"/[lang]">) {
  const { lang } = await params;
  if (!isLocale(lang)) notFound();

  return (
    <main lang={lang}>
      <h1 className="text-3xl font-semibold">{text[lang].title}</h1>
      <p className="pt-2">{text[lang].body}</p>
      <p className="pt-4 text-sm">
        {locales.map((other) => (
          <Link key={other} href={`/${other}`} className="pr-3">
            {other}
          </Link>
        ))}
      </p>
    </main>
  );
}
TSX
cat > "src/app/docs/v2/[topic]/page.tsx" <<'TSX'
import { notFound } from "next/navigation";

const topics: Record<string, { title: string; body: string }> = {
  install: { title: "Install", body: "Run npm install, then npm run dev." },
  "getting-started": { title: "Getting started", body: "Create your first page." },
};

export function generateStaticParams() {
  return Object.keys(topics).map((topic) => ({ topic }));
}

export default async function DocPage({ params }: PageProps<"/docs/v2/[topic]">) {
  const { topic } = await params;
  const doc = Object.hasOwn(topics, topic) ? topics[topic] : undefined;
  if (!doc) notFound();

  return (
    <main>
      <p className="text-sm">Docs version 2</p>
      <h1 className="text-2xl font-semibold">{doc.title}</h1>
      <p className="pt-2">{doc.body}</p>
    </main>
  );
}
TSX

Start the dev server in a second terminal, from ~/proxy-demo, and leave it running for the next four steps:

Bash
npm run dev

Check it worked

Request one home page and one docs page:

Bash
curl -s http://localhost:3000/sw | grep -o '<h1[^>]*>[^<]*</h1>'
curl -s http://localhost:3000/docs/v2/install | grep -o '<h1[^>]*>[^<]*</h1>'

The output is the heading Karibu, then the heading Install. There is no page at / yet, so http://localhost:3000/ shows a 404 page for now.

Step 3 · Redirect old URLs from a map

Sites move pages. Links in old emails, search results and other people's sites keep pointing at the old address, and each one should land somewhere useful. Keep the moves in a lookup table, separate from the proxy logic, so anyone can add a row without reading the rest:

Bash
cd ~/proxy-demo
cat > src/lib/redirect-map.ts <<'TS'
// Old path -> new path. Point every entry at a final address,
// never at another old path, so a visitor gets one hop, not a chain.
export const redirectMap = new Map<string, string>([
  ["/home", "/"],
  ["/help", "/docs/latest/getting-started"],
  ["/docs/v1/install", "/docs/latest/install"],
  ["/docs/v1/getting-started", "/docs/latest/getting-started"],
  ["/sign-in", "/login"],
]);
TS

Now create the proxy. It looks up the path, and for a match, answers with a 308 redirect, keeping any query string such as ?ref=newsletter. Everything else carries on with NextResponse.next(). The matcher keeps the proxy away from Next.js's own build files and images, which never need it:

Bash
cd ~/proxy-demo
cat > src/proxy.ts <<'TS'
import { NextResponse, type NextRequest } from "next/server";
import { redirectMap } from "@/lib/redirect-map";

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  const target = redirectMap.get(pathname);
  if (target) {
    const url = request.nextUrl.clone();
    url.pathname = target;
    return NextResponse.redirect(url, 308);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml).*)"],
};
TS

A 308 tells browsers and search engines that the move is permanent, so they update their records. Without the second argument, NextResponse.redirect sends a 307, a temporary redirect, which is right for moves that depend on the visitor, as in the next steps.

For a short list of fixed moves, the redirects option in next.config.ts does the same job without any code, and runs before the proxy. The proxy earns its place when a rule needs the request itself (cookies, headers, the language) or when you want the map, the language choice and the sign-in check in one file you can read top to bottom, as here.

Check it worked

Ask for an old URL without following the redirect. -w prints the status code and where the redirect points:

Bash
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' 'http://localhost:3000/help?ref=newsletter'
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://localhost:3000/en

The first line is 308 http://localhost:3000/docs/latest/getting-started?ref=newsletter. The second is 200 with nothing after it, because /en is not in the map and passes straight through. The redirect target does not exist yet; the next step makes it work.

If the redirect does not happen, check that the file is src/proxy.ts, not proxy.ts in the project root, and look at the dev server terminal for a compile error.

Step 4 · Rewrite a path and add a request header

A redirect changes the address in the browser. A rewrite does not: the visitor asks for /docs/latest/install, sees that address, and Next.js renders /docs/v2/install. When version 3 of the docs ships, you change one line and every "latest" link moves with it.

The same step adds a header. Each request gets an x-request-id, a random ID that your server code can write into its logs, and that the visitor sees in the response, so a support report can quote it. Setting it on the request uses NextResponse.next({ request: { headers } }), which passes headers on to your pages and route handlers. Headers set with response.headers.set go back to the browser. Mixing the two up is a common mistake: passing request headers as NextResponse.next({ headers }) sends them to the browser instead.

Replace the proxy with this version:

Bash
cd ~/proxy-demo
cat > src/proxy.ts <<'TS'
import { NextResponse, type NextRequest } from "next/server";
import { redirectMap } from "@/lib/redirect-map";

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // 1. Old URLs: one permanent redirect per entry in the map.
  const target = redirectMap.get(pathname);
  if (target) {
    const url = request.nextUrl.clone();
    url.pathname = target;
    return NextResponse.redirect(url, 308);
  }

  // 2. Every other request gets an ID, for the app and for the browser.
  const requestId = crypto.randomUUID();
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-request-id", requestId);

  // 3. /docs/latest/... is served by /docs/v2/... and the address stays the same.
  let response: NextResponse;
  if (pathname === "/docs/latest" || pathname.startsWith("/docs/latest/")) {
    const url = request.nextUrl.clone();
    url.pathname = "/docs/v2" + pathname.slice("/docs/latest".length);
    response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });
  } else {
    response = NextResponse.next({ request: { headers: requestHeaders } });
  }

  response.headers.set("x-request-id", requestId);
  return response;
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml).*)"],
};
TS

To see the request header arrive inside the app, add a small route handler that reports it:

Bash
cd ~/proxy-demo
mkdir -p src/app/api/request-id
cat > src/app/api/request-id/route.ts <<'TS'
import type { NextRequest } from "next/server";

export function GET(request: NextRequest) {
  return Response.json({ requestId: request.headers.get("x-request-id") });
}
TS

Check it worked

Fetch the "latest" docs page, then the route handler with its headers:

Bash
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://localhost:3000/docs/latest/install
curl -s http://localhost:3000/docs/latest/install | grep -o '<h1[^>]*>[^<]*</h1>'
curl -s -i http://localhost:3000/api/request-id | grep -i -e '^x-request-id' -e requestId

The first line is 200 with no redirect address: the browser would stay on /docs/latest/install. The second prints the heading Install from the version 2 page. The third prints an x-request-id header and a JSON body such as {"requestId":"6f0c…"} with the same ID in both, which shows that the header reached the route handler and the browser.

Step 5 · Send visitors to their language

There is no page at /. The proxy answers it by reading the visitor's languages and redirecting to /en, /fr or /sw. A visitor who chose a language before, stored in a locale cookie by a language switcher, gets that choice first, because the browser setting is often only a guess: many people use a phone set to English but read French or Swahili more comfortably, and a phone bought second-hand may carry someone else's setting. That is also why the home page keeps visible links to every language. Do not guess the language from the visitor's IP address or country; people travel and countries are multilingual.

Replace the proxy with this version. The new part is section 2, right after the redirect map:

Bash
cd ~/proxy-demo
cat > src/proxy.ts <<'TS'
import { NextResponse, type NextRequest } from "next/server";
import { redirectMap } from "@/lib/redirect-map";
import { isLocale, pickLocale } from "@/lib/locale";

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // 1. Old URLs: one permanent redirect per entry in the map.
  const target = redirectMap.get(pathname);
  if (target) {
    const url = request.nextUrl.clone();
    url.pathname = target;
    return NextResponse.redirect(url, 308);
  }

  // 2. The bare home page: a saved choice first, then the browser's languages.
  if (pathname === "/") {
    const saved = request.cookies.get("locale")?.value;
    const locale = isLocale(saved) ? saved : pickLocale(request.headers.get("accept-language"));
    const url = request.nextUrl.clone();
    url.pathname = `/${locale}`;
    const response = NextResponse.redirect(url, 307);
    response.headers.set("Vary", "Accept-Language, Cookie");
    return response;
  }

  // 3. Every other request gets an ID, for the app and for the browser.
  const requestId = crypto.randomUUID();
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-request-id", requestId);

  // 4. /docs/latest/... is served by /docs/v2/... and the address stays the same.
  let response: NextResponse;
  if (pathname === "/docs/latest" || pathname.startsWith("/docs/latest/")) {
    const url = request.nextUrl.clone();
    url.pathname = "/docs/v2" + pathname.slice("/docs/latest".length);
    response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });
  } else {
    response = NextResponse.next({ request: { headers: requestHeaders } });
  }

  response.headers.set("x-request-id", requestId);
  return response;
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml).*)"],
};
TS

The redirect is a 307, a temporary one, because the answer depends on who is asking. The Vary header tells any cache between you and the visitor that the answer changes with the language header and cookies, so one visitor's French redirect is not served to the next visitor.

Check it worked

Send three different visitors to /:

Bash
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -H 'Accept-Language: sw-KE,sw;q=0.9,en;q=0.8' http://localhost:3000/
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -H 'Accept-Language: de-DE,fr;q=0.7' http://localhost:3000/
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -H 'Accept-Language: sw-KE' -b 'locale=fr' http://localhost:3000/

The output is 307 http://localhost:3000/sw, then 307 http://localhost:3000/fr (German is not offered, so French, the next choice, wins), then 307 http://localhost:3000/fr again, because the saved cookie beats the header.

Step 6 · Send signed-out visitors to the login page

The account page is for signed-in people. The proxy can turn away visitors who have no session cookie at all, before Next.js renders anything. That is a quick, cheap filter. It is not security: anyone can send a cookie called session with any value. The real check reads and verifies the session where the data is used, in this case inside the account page.

This demo signs a session cookie with an HMAC so the page can tell a real cookie from a made-up one. The key comes from an environment variable, never from the code. Create .env.local private from the start, with a random 32-byte key:

Bash
cd ~/proxy-demo
(umask 077 && printf 'SESSION_SECRET=%s\n' "$(node -e 'console.log(require("node:crypto").randomBytes(32).toString("hex"))')" > .env.local)
ls -l .env.local
grep -n '^\.env' .gitignore

ls shows -rw-------, readable by you alone, and grep shows that the project's .gitignore already keeps .env files out of Git.

The session module signs and verifies the cookie. The account page calls getSession(), and so would every server action or data function that reads or changes this user's data:

Bash
cd ~/proxy-demo
cat > src/lib/session.ts <<'TS'
import { createHmac, timingSafeEqual } from "node:crypto";
import { cookies } from "next/headers";

function secret(): string {
  const value = process.env.SESSION_SECRET;
  if (!value || value.length < 32) {
    throw new Error("Set SESSION_SECRET (32+ characters) in .env.local");
  }
  return value;
}

function sign(payload: string): string {
  return createHmac("sha256", secret()).update(payload).digest("base64url");
}

export function createSessionValue(name: string): string {
  const payload = Buffer.from(name, "utf8").toString("base64url");
  return `${payload}.${sign(payload)}`;
}

export async function getSession(): Promise<{ name: string } | null> {
  const value = (await cookies()).get("session")?.value;
  if (!value) return null;
  const [payload, signature] = value.split(".");
  if (!payload || !signature) return null;
  const expected = Buffer.from(sign(payload));
  const given = Buffer.from(signature);
  if (expected.length !== given.length || !timingSafeEqual(expected, given)) return null;
  return { name: Buffer.from(payload, "base64url").toString("utf8") };
}
TS

Now a login page, a route handler that sets the cookie, and the account page. The login page carries the next address the proxy adds, and the handler only follows it when it is a path on this site, so nobody can use your login form to bounce people to another domain:

Bash
cd ~/proxy-demo
mkdir -p src/app/login src/app/account src/app/api/login
cat > src/app/login/page.tsx <<'TSX'
import { Suspense } from "react";

type SearchParams = Promise<Record<string, string | string[] | undefined>>;

async function LoginForm({ searchParams }: { searchParams: SearchParams }) {
  const { next } = await searchParams;
  return (
    <form method="post" action="/api/login" className="flex flex-col gap-3 pt-4">
      <input type="hidden" name="next" defaultValue={typeof next === "string" ? next : "/account"} />
      <label>
        Your name <input name="name" required className="rounded border px-2 py-1" />
      </label>
      <button type="submit" className="w-fit rounded border px-3 py-1">Sign in</button>
    </form>
  );
}

export default function LoginPage({ searchParams }: PageProps<"/login">) {
  return (
    <main>
      <h1 className="text-2xl font-semibold">Sign in</h1>
      <Suspense fallback={null}>
        <LoginForm searchParams={searchParams} />
      </Suspense>
    </main>
  );
}
TSX
cat > src/app/api/login/route.ts <<'TS'
import { NextResponse, type NextRequest } from "next/server";
import { createSessionValue } from "@/lib/session";

// Demo sign-in: anyone with a name gets a session. Real apps check a password
// or use an auth library here.
export async function POST(request: NextRequest) {
  const form = await request.formData();
  const name = String(form.get("name") ?? "").trim().slice(0, 40) || "reader";
  const next = String(form.get("next") ?? "");
  const target = next.startsWith("/") && !next.startsWith("//") ? next : "/account";

  const response = NextResponse.redirect(new URL(target, request.url), 303);
  response.cookies.set("session", createSessionValue(name), {
    httpOnly: true,
    sameSite: "lax",
    secure: process.env.NODE_ENV === "production",
    path: "/",
    maxAge: 60 * 60 * 8,
  });
  return response;
}
TS
cat > src/app/account/page.tsx <<'TSX'
import Link from "next/link";
import { Suspense } from "react";
import { getSession } from "@/lib/session";

async function AccountDetails() {
  // The real check: verify the session where the data is read.
  const session = await getSession();
  if (!session) {
    return (
      <p className="pt-2">
        Your session is not valid. <Link href="/login?next=/account">Sign in again</Link>.
      </p>
    );
  }
  return <p className="pt-2">{`Signed in as ${session.name}.`}</p>;
}

export default function AccountPage() {
  return (
    <main>
      <h1 className="text-2xl font-semibold">Your account</h1>
      <Suspense fallback={<p className="pt-2">Checking your session…</p>}>
        <AccountDetails />
      </Suspense>
    </main>
  );
}
TSX

Finally, the proxy rule. Replace src/proxy.ts with this version. The new part is section 2b, between the home page rule and the request ID:

Bash
cd ~/proxy-demo
cat > src/proxy.ts <<'TS'
import { NextResponse, type NextRequest } from "next/server";
import { redirectMap } from "@/lib/redirect-map";
import { isLocale, pickLocale } from "@/lib/locale";

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // 1. Old URLs: one permanent redirect per entry in the map.
  const target = redirectMap.get(pathname);
  if (target) {
    const url = request.nextUrl.clone();
    url.pathname = target;
    return NextResponse.redirect(url, 308);
  }

  // 2. The bare home page: a saved choice first, then the browser's languages.
  if (pathname === "/") {
    const saved = request.cookies.get("locale")?.value;
    const locale = isLocale(saved) ? saved : pickLocale(request.headers.get("accept-language"));
    const url = request.nextUrl.clone();
    url.pathname = `/${locale}`;
    const response = NextResponse.redirect(url, 307);
    response.headers.set("Vary", "Accept-Language, Cookie");
    return response;
  }

  // 2b. A quick filter, not security: no session cookie, no account page.
  if (pathname.startsWith("/account") && !request.cookies.has("session")) {
    const url = request.nextUrl.clone();
    url.pathname = "/login";
    url.search = "";
    url.searchParams.set("next", pathname);
    return NextResponse.redirect(url, 307);
  }

  // 3. Every other request gets an ID, for the app and for the browser.
  const requestId = crypto.randomUUID();
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set("x-request-id", requestId);

  // 4. /docs/latest/... is served by /docs/v2/... and the address stays the same.
  let response: NextResponse;
  if (pathname === "/docs/latest" || pathname.startsWith("/docs/latest/")) {
    const url = request.nextUrl.clone();
    url.pathname = "/docs/v2" + pathname.slice("/docs/latest".length);
    response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });
  } else {
    response = NextResponse.next({ request: { headers: requestHeaders } });
  }

  response.headers.set("x-request-id", requestId);
  return response;
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml).*)"],
};
TS

Next.js reloads .env.local and proxy.ts while the dev server runs. If the account page later says SESSION_SECRET is missing, stop the dev server with Ctrl+C and start it again.

Check it worked

Walk through it as three visitors: one with no cookie, one who signs in, and one who makes up a cookie:

Bash
cd ~/proxy-demo
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://localhost:3000/account
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -c cookies.txt -d 'name=Amina' -d 'next=/account' http://localhost:3000/api/login
curl -s -b cookies.txt http://localhost:3000/account | grep -o 'Signed in as [A-Za-z]*\.' | head -n 1
curl -s -b 'session=made-up.value' http://localhost:3000/account | grep -o 'Your session is not valid' | head -n 1

The output is:

Text
307 http://localhost:3000/login?next=%2Faccount
303 http://localhost:3000/account
Signed in as Amina.
Your session is not valid

The last line is the point of this step. The made-up cookie got past the proxy, because the proxy only checks that a cookie exists, and the page's own check stopped it. In a real app, put getSession() (or your auth library's equivalent) in every data function and server action, not only in pages. A proxy matcher that skips a route also skips the server actions on that route, so the proxy alone can leave a gap. Sign in librarians with Better Auth shows that pattern with a full auth library.

Step 7 · Keep slow work out of the proxy

The proxy runs before every matched request, including the background prefetches that each <Link> on a page triggers. Anything it waits for, every visitor waits for, before the first byte of the page. The tempting mistake looks like this. Do not write it:

TypeScript
// Do not do this: a database round trip on every request.
export async function proxy(request: NextRequest) {
  const token = request.cookies.get("session")?.value;
  const user = await db.query.users.findFirst({ where: eq(users.token, token) });
  if (!user?.isAdmin && request.nextUrl.pathname.startsWith("/admin")) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
}

It adds a database query to every page view, prefetch and form post, and there is no way to cache it in the proxy: "use cache" has no effect there, and neither do the caching options on fetch. It also gives a false sense of safety, because the admin data is still unprotected wherever the proxy does not run. Do the cheap cookie check in the proxy, as you did, and the database check in the code that loads admin data.

Other things that belong elsewhere: fixed redirects with no logic (redirects in next.config.ts), CORS and caching headers for one API (the route handler itself), and anything that needs the page's data. Keep the proxy short enough to read in one screen.

Check it worked

Your proxy awaits nothing and makes no network calls:

Bash
cd ~/proxy-demo
grep -nE 'await|fetch\(' src/proxy.ts || echo "proxy.ts makes no awaited calls"

The output is proxy.ts makes no awaited calls. If grep prints a line instead, look hard at what that line waits for.

Step 8 · Test the redirect map against a production build

Stop the dev server with Ctrl+C in its terminal.

Write the expected results next to the code, one line per URL: the path, the status code and the redirect address, or - for none. The script reads each line, asks the server with curl, and reports every mismatch:

Bash
cd ~/proxy-demo
cat > redirects.txt <<'TXT'
/home 308 /
/help 308 /docs/latest/getting-started
/help?ref=newsletter 308 /docs/latest/getting-started?ref=newsletter
/docs/v1/install 308 /docs/latest/install
/docs/v1/getting-started 308 /docs/latest/getting-started
/sign-in 308 /login
/docs/latest/install 200 -
/en 200 -
/account 307 /login?next=%2Faccount
TXT
cat > check-redirects.sh <<'SH'
#!/usr/bin/env bash
# Usage: bash check-redirects.sh [base URL]
base="${1:-http://localhost:3000}"
failures=0
while read -r path want_status want_location; do
  [ -z "$path" ] && continue
  want_url=""
  [ "$want_location" != "-" ] && want_url="$base$want_location"
  got=$(curl -s -o /dev/null -w '%{http_code} %{redirect_url}' "$base$path")
  got_status="${got%% *}"
  got_url="${got#* }"
  if [ "$got_status" = "$want_status" ] && [ "$got_url" = "$want_url" ]; then
    echo "ok    $path -> $want_status $want_location"
  else
    echo "FAIL  $path: wanted $want_status $want_url, got $got_status $got_url"
    failures=$((failures + 1))
  fi
done < redirects.txt
echo "$failures failure(s)"
[ "$failures" -eq 0 ]
SH

Build the app, then start the production server in your second terminal:

Bash
cd ~/proxy-demo
npm run build
Bash
npm run start

Run the checks:

Bash
cd ~/proxy-demo
bash check-redirects.sh http://localhost:3000

Check it worked

Every line starts with ok, and the last line is 0 failure(s). The script exits with status 0, so it can run as a CI job after a build. To see a failure, change /sign-in 308 /login to /sign-in 308 /log-in in redirects.txt and run the script again: that line starts with FAIL, the count goes to 1 and the exit status is 1. Change it back afterwards.

Open http://localhost:3000/ in a browser too. It lands on the home page in your browser's language, and /docs/latest/install keeps that address in the address bar while showing the version 2 page.

Stop the production server with Ctrl+C.

Step 9 · Remove the demo project

The project holds a session key in .env.local and a cookie file, so delete the whole folder when you finish:

Bash
cd ~
rm -rf ~/proxy-demo

Check it worked

ls ~/proxy-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.