CodePark/ questions / Route handlers & middleware
START PRACTICINGPRACTICE
Frontend question · Next.js › Route handlers & middleware

What is middleware (proxy in Next.js 16) used for, and what are its limits?

// middleware.ts (proxy.ts with export function proxy in Next.js 16)
import { NextResponse, type NextRequest } from "next/server";

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

export const config = { matcher: ["/dashboard/:path*"] };

Middleware runs before a request reaches a route. It can redirect, rewrite, set headers and cookies, or return a response itself.

Typical uses:

  • optimistic auth redirects, based only on whether a session cookie exists
  • locale detection
  • A/B testing
  • bot filtering
  • adding security headers

A matcher config limits which paths it runs on.

Limits:

  • It runs on every matched request, including prefetches. So it must stay fast. Avoid slow database calls there.
  • Don't treat it as your only authorization check. Check again where data is read or changed.
  • A project has only one middleware file, at the root or inside src.

Next.js 16: the file is renamed to proxy.ts, with an exported proxy function. middleware.ts is deprecated.

  • Middleware runs before routing and can redirect, rewrite or set headers and cookies.
  • Common uses are optimistic auth, i18n, A/B tests and security headers.
  • Use matcher to limit which paths it runs on.
  • Keep it fast, and never make it the only auth check.
  • In Next.js 16, middleware is renamed to proxy.ts.