Skip to article content
FrontendXLesson 16 / 20

Proxy and Middleware: the Request Gatekeeper

A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.

intermediate · about 50 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Write a proxy function with a scoped matcher that redirects, rewrites or annotates requests.
  • Explain why proxy checks are a perimeter control and where the real authorization must live.
  • Migrate from the Next.js 15 middleware.ts convention to the Next.js 16 proxy.ts convention.

Overview

#

One function before every matched request

The App Router lets you register a single function that runs before a request reaches your routes. It can redirect, rewrite the URL, set or read cookies, and add response headers. In Next.js 15 and earlier this file is middleware.ts and the exported function is named middleware. Next.js 16 renames the convention to proxy.ts with a named export proxy; new projects should use the new name and existing projects migrate the file during the upgrade. The behavior you can implement is unchanged: the rename is about naming the job honestly, gating and adjusting requests.

snippet.ts
// proxy.ts  (middleware.ts in Next.js 15 and earlier)
import { NextResponse, type NextRequest } from "next/server";

export function proxy(request: NextRequest) {
  const session = request.cookies.get("session")?.value;
  if (!session && request.nextUrl.pathname.startsWith("/dashboard")) {
    const login = new URL("/login", request.url);
    login.searchParams.set("next", request.nextUrl.pathname);
    return NextResponse.redirect(login);
  }
  const response = NextResponse.next();
  response.headers.set("x-request-id", crypto.randomUUID());
  return response;
}

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

Scope it or pay for it

Without config.matcher the function runs on every request, including static assets and prefetches, which multiplies its cost across your whole traffic. The matcher is a route pattern list; use :path* for segment wildcards and keep the list as short as the feature requires. Runtime note: the old middleware.ts convention ran on the Edge runtime with a restricted API surface, but Next.js 16 proxy.ts defaults to the Node.js runtime and its runtime config option is not available, so the Edge-era guidance to avoid Node APIs no longer applies. Keep the function light anyway: it runs before every matched request, so cookie reads, header math and URL decisions stay cheap, and heavier work belongs in the route or data layer it guards.

A perimeter, not a boundary

A proxy check is a convenience gate, not your security model. It runs before rendering, but it cannot see what a server action or route handler does internally, and a missing matcher entry silently opens a hole. Treat it as the bouncer at the door: unauthenticated users bounce fast from /dashboard, while every data access layer function still verifies the session itself. Defense in depth means the proxy saves latency and the data layer guarantees correctness.

Cookies across the gate

request.cookies reads incoming cookies and response.cookies sets them, which makes the proxy the natural place to rotate a session token or drop an expired one. A classic bug is setting a cookie on one response object and returning a different one; the cookie lives and dies with the response you actually return.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    Given this proxy and config, what happens for each request? export function proxy(request: NextRequest) { if (!request.cookies.get('session') && request.nextUrl.pathname.startsWith('/dashboard')) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } export const config = { matcher: ['/dashboard/:path*'] }; Request 1: GET /dashboard Request 2: GET /about Request 3: GET /dashboard/settings with a session cookie

    Choose the best answer
  2. Exercise 2Explain

    Explain in your own words why a proxy redirect is not sufficient authorization, and name the layer where the real check must live.

    Reveal the reference answer
    reference.text
    The proxy runs before rendering and can bounce unauthenticated traffic, but it cannot see inside server actions, route handlers or data functions, and a matcher gap silently bypasses it. The real authorization check must live in the data access layer: every function that reads or writes privileged data verifies the session itself, so correctness does not depend on the perimeter.

    Authored expected output: A statement that the proxy is a perimeter gate plus the naming of the data access layer as the enforcement point.

    Perimeter controls improve latency and UX; correctness requires enforcement at the point where data is touched.

  3. Exercise 3Implement

    Write proxy.ts for a Next.js 16 app: unauthenticated users visiting /dashboard or any nested path are redirected to /login with their destination preserved in a next query parameter, authenticated users pass through, and the proxy runs only for dashboard paths.

    starter.ts
    // proxy.ts
    import { NextResponse, type NextRequest } from 'next/server';
    
    export function proxy(request: NextRequest) {
      // TODO
    }
    
    export const config = {
      // TODO: matcher
    };

    Reveal the reference answer
    reference.ts
    import { NextResponse, type NextRequest } from 'next/server';
    
    export function proxy(request: NextRequest) {
      const session = request.cookies.get('session')?.value;
      if (!session) {
        const login = new URL('/login', request.url);
        login.searchParams.set('next', request.nextUrl.pathname + request.nextUrl.search);
        return NextResponse.redirect(login);
      }
      return NextResponse.next();
    }
    
    export const config = {
      matcher: ['/dashboard/:path*'],
    };

    Authored expected output: Visits to /dashboard and /dashboard/settings without a session cookie land on /login?next=%2Fdashboard..., and authenticated users reach the dashboard.

    new URL('/login', request.url) builds an absolute redirect target, nextUrl carries the original path and search, and the matcher keeps the function off every other route.

  4. Exercise 4Debug

    This proxy is supposed to log users in by setting a session cookie, but the cookie never persists across navigation. Find the bug. export function proxy(request: NextRequest) { const token = request.headers.get('x-token'); if (token && !request.cookies.get('session')) { const response = NextResponse.next(); response.cookies.set('session', token, { httpOnly: true }); } const finalResponse = NextResponse.next(); finalResponse.headers.set('x-frame-options', 'DENY'); return finalResponse; }

    starter.ts
    export function proxy(request: NextRequest) {
      const token = request.headers.get('x-token');
      if (token && !request.cookies.get('session')) {
        const response = NextResponse.next();
        response.cookies.set('session', token, { httpOnly: true });
      }
      const finalResponse = NextResponse.next();
      finalResponse.headers.set('x-frame-options', 'DENY');
      return finalResponse;
    }

    Reveal the reference answer
    reference.ts
    The cookie is set on the first response object but a second, fresh NextResponse.next() is created and returned, so the cookie header is discarded. Build one response, mutate it, and return that same object:
    
    const response = NextResponse.next();
    if (token && !request.cookies.get('session')) {
      response.cookies.set('session', token, { httpOnly: true });
    }
    response.headers.set('x-frame-options', 'DENY');
    return response;

    Authored expected output: The session cookie appears in the returned response's Set-Cookie header and persists on the next request.

    Cookies travel on the response you return. Creating a second response after setting the cookie throws the Set-Cookie header away.

  5. Exercise 5Test

    Extract the gate decision into a pure function decideGate(pathname: string, hasSession: boolean) that returns 'redirect' or 'pass', and write assertions covering: /dashboard without session, /dashboard/settings with session, /about without session, and /dashboard with session.

    starter.ts
    export function decideGate(pathname: string, hasSession: boolean): 'redirect' | 'pass' {
      // TODO
    }
    
    // assertions
    // expect(decideGate('/dashboard', false)).toBe('redirect')
    // expect(decideGate('/dashboard/settings', true)).toBe('pass')
    // expect(decideGate('/about', false)).toBe('pass')
    // expect(decideGate('/dashboard', true)).toBe('pass')

    Reveal the reference answer
    reference.ts
    export function decideGate(pathname: string, hasSession: boolean): 'redirect' | 'pass' {
      const isProtected = pathname === '/dashboard' || pathname.startsWith('/dashboard/');
      if (isProtected && !hasSession) return 'redirect';
      return 'pass';
    }
    
    // '/dashboard/settings' starts with '/dashboard/' so it is protected; the session lets it pass.
    // '/about' is outside the gate entirely, so it passes even without a session.

    Authored expected output: All four assertions pass: redirect, pass, pass, pass.

    Pure decision logic is testable without a request object; the proxy becomes a thin adapter that feeds pathname and cookie presence into the function.

  6. Exercise 6Interview

    Interview question: your team ships a large app with role-based access. Where do you enforce authentication and authorization across proxy, layouts, server actions and route handlers, and why that split?

    Reveal the reference answer
    reference.text
    The proxy handles coarse gating: bounce obviously unauthenticated traffic away from protected URL prefixes cheaply, before any rendering work. Fine-grained authorization lives at the data access layer: every function that touches privileged data verifies the session and role itself, because server actions and route handlers are independently reachable endpoints that must not trust the perimeter. Layouts add UI-level affordances like hiding links, never enforcement. This split means a matcher bug degrades UX, not security, and every entry point fails closed.

    Authored expected output: A layered answer naming proxy for coarse gating, the data access layer for enforcement, and independent verification in server actions and route handlers.

    Strong answers recognize that any single choke point is bypassable and that endpoints are the real trust boundary.

Common misconceptions

#
  • The proxy is the authorization layer. It is a perimeter gate; every privileged data access must still verify the session itself.
  • The middleware file runs only on page navigations. Without a matcher it runs on every matched request, including assets and prefetches.

Follow-up practice

#
  • nextjs-images-env-config
  • nextjs-deployment-capstone

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.