पाठ 18 / 25

Proxy (Formerly Middleware)

Run code before a request is completed.

Redirects, rewrites and headers before rendering

A proxy.ts file at the project root exports a proxy function that runs before matching requests. It can redirect, rewrite, read or set cookies and headers, typically for coarse checks such as "send users without a session cookie to the login page". In Next.js 16 this convention was renamed from middleware to proxy (the old name is deprecated). Keep proxy logic light and do not rely on it alone for security: still check authorisation where data is read and changed. Next.js changes quickly between major versions; check the docs for your version (they ship inside node_modules/next/dist/docs).

A login guard for /admin

This file is from a small demo store I built with Next.js 16.3.8, React 19.3 and TypeScript; next build compiled and type-checked it successfully. The matcher limits the proxy to /admin paths; requests without a session cookie are redirected to /login.

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

export function proxy(request: NextRequest) {
  if (!request.cookies.has("session")) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: "/admin/:path*" };

Requesting /admin with and without a cookie, run

I built the demo store with next build (Next.js 16.3.8), started it with next start and requested pages with curl; the output is copied from that run, trimmed to the relevant lines. Without the cookie the proxy answers with a 307 redirect to /login; with a session cookie the page loads (200). The build output lists the proxy as "ƒ Proxy (Middleware)".

curl -s -o /dev/null -w "no cookie: %{http_code} -> %{redirect_url}" http://localhost:3917/admin
curl -s -o /dev/null -w "with cookie: %{http_code}" -b "session=abc" http://localhost:3917/admin

Output:

no cookie: 307 -> http://localhost:3917/login
with cookie: 200

त्वरित जाँच: Should a proxy cookie check be your only authorisation?

  • No, also check permissions where data is read and changed
  • Yes, it is sufficient
  • Only for GET requests
  • Only in production
Answer

No, also check permissions where data is read and changed — Defence in depth.