Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 72 ยท Middleware, Proxy and Auth

Middleware and the Proxy File

Learn what Next.js middleware does, how it became proxy.ts in version 16, how the matcher works, and how to redirect, rewrite and add headers, plus its limits.

Sometimes you need to act on a request before any page is rendered: send a visitor who is not logged in to the login page, show half of your visitors a different pricing page, add a header to every response, or rewrite an old URL. Next.js has one place for that: a single file that runs in front of your routes and can answer the request itself, change it, or let it through.

In Next.js 15 and earlier this file is called middleware (middleware.ts). Version 16 renames it to proxy (proxy.ts) because the name "middleware" suggested something like Express middleware, while the file really behaves like a small network layer at the edge of your app. The idea is the same, and the migration is mostly a rename. This lesson covers both names, the matcher that controls which requests it sees, what you can do inside it, and the limits that should keep you from putting too much in it.

A proxy file only runs inside a real Next.js server, which this site cannot start. The Next.js code below is read-only. The two runnable examples are stand-ins: one rebuilds the matcher pattern matching, the other mimics a proxy function that returns redirect, rewrite or pass-through decisions.

Where it sits in the request

One file, before the routes

proxy.ts At the project root, next to app. Only one per project.
Matcher Decides which requests it runs for.
Decision Redirect, rewrite or continue.

In Next.js 15 and earlier, the same file is middleware.ts.

1 / 3
flowchart LR
  A["Browser request"] --> B["proxy.ts<br/>(if the matcher matches)"]
  B -->|"redirect"| C["Browser goes to a new URL"]
  B -->|"rewrite"| D["Another route renders,<br/>URL stays the same"]
  B -->|"next()"| E["Route renders as usual"]

The proxy runs first and picks one of three outcomes.

Your first proxy file

Create proxy.ts next to the app folder (or inside src if you use one) and export a function:

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

export function proxy(request: NextRequest) {
  const hasSession = request.cookies.has('session');

  if (!hasSession) {
    const loginUrl = new URL('/login', request.url);
    loginUrl.searchParams.set('from', request.nextUrl.pathname);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

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

Everything comes from next/server. The function receives a NextRequest, which is the Web Request plus conveniences such as request.cookies and request.nextUrl (a parsed URL you can read and clone). It returns a NextResponse, and the three factory methods you will use are:

  • NextResponse.next() continues to the route.
  • NextResponse.redirect(url) answers with a redirect. The default status is 307, and you can pass 308 for a permanent one.
  • NextResponse.rewrite(url) renders another route but leaves the address bar alone.

You can export the function as proxy or as the default export. In Next.js 15, the file is named middleware.ts and the function is named middleware.

Migrating to 16. Rename middleware.ts to proxy.ts and the exported function to proxy. Next.js ships a codemod for it (npx @next/codemod@canary middleware-to-proxy .). A file called middleware.ts still works for now but is deprecated, and a few config flags were renamed too. Check the upgrade guide of your version, or see Upgrading and Migrating from Pages Router.

The matcher

Without a config.matcher, the proxy runs for every request, including images, scripts and fonts. That is almost never what you want. The matcher lists the paths it should handle:

TypeScript
export const config = {
  matcher: [
    '/dashboard/:path*',        // /dashboard and everything below it
    '/account/:id',             // exactly one segment after /account
    '/((?!api|_next/static|_next/image|favicon.ico).*)', // everything except these
  ],
};

The syntax follows path-to-regexp. The part to learn:

Pattern Meaning
:name exactly one segment
:name* zero or more segments
:name+ one or more segments
:name? zero or one segment
(regex) a custom regular expression

Values must be constants: Next.js reads the matcher at build time, so you cannot compute it from a variable. Each entry must start with /. For finer control you can use an object with source, has and missing, which match on headers, cookies or query values:

TypeScript
export const config = {
  matcher: [
    {
      source: '/dashboard/:path*',
      missing: [{ type: 'header', key: 'next-router-prefetch' }], // skip prefetches
    },
  ],
};

The first runnable example rebuilds the matcher idea so you can try patterns and see which requests they catch. This is a simplified stand-in for path-to-regexp, enough to show the rules, including a well-known trap in the "everything except" pattern.

Node.js Which paths does a matcher catch?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the table column by column. m1 catches /dashboard and everything below it but not /dashboardx, because :path* needs a slash before any extra segment. m2 wants exactly one segment, so /blog alone does not match. The third pattern, "everything except api, _next/static, _next/image and favicon.ico", catches /about, but look at /apiary: it is excluded too, because the lookahead (?!api...) only checks that the path starts with api. That is how the pattern behaves in real Next.js as well. If you use it, remember that any top-level route whose name begins with api escapes the proxy, and prefer a /api/ form with a trailing slash when you can.

What you can do inside

Redirect and rewrite

A redirect changes the URL the visitor sees. A rewrite does not: the address bar shows /pricing, but the page that renders is /pricing-b. Rewrites are how you serve a variant, map a friendly URL onto a different route, or point a locale-less path at /en/....

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

  if (pathname === '/old-blog') {
    return NextResponse.redirect(new URL('/blog', request.url), 308);
  }

  if (pathname === '/pricing') {
    return NextResponse.rewrite(new URL('/pricing-b', request.url));
  }

  return NextResponse.next();
}

Headers and cookies

You can add headers to the response the browser sees, and also to the request that your routes receive. The second form is how a proxy hands information to a page, for example a request id that headers() reads later (see Cookies and Headers):

TypeScript
export function proxy(request: NextRequest) {
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-request-id', crypto.randomUUID());

  const response = NextResponse.next({ request: { headers: requestHeaders } });
  response.headers.set('x-frame-options', 'DENY');
  response.cookies.set('visited', '1', { path: '/', sameSite: 'lax' });
  return response;
}

A/B testing

A simple experiment keeps a visitor's variant in a cookie. The first time they arrive, the proxy picks a variant and stores it, and from then on it rewrites to the same variant. The URL stays /pricing, so links and analytics do not change. One thing to remember: a page that varies by cookie cannot be served from a shared cache without taking the cookie into account, so check your CDN rules before you ship an experiment.

The second example runs a proxy function against a few requests and prints the decision for each. It mimics NextResponse with plain objects.

Node.js A proxy that redirects, rewrites and tags requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output shows the three outcomes plus the cases where nothing happens. An anonymous request to /dashboard/orders is redirected, with the original path stored in from so that the login page can send the visitor back. The same request with a session cookie continues. Visitors ana and bo land in different buckets, and the proxy hands the first one a Set-Cookie so they stay there, while the visitor who already has bucket=b gets the variant without a new cookie. /about never reaches the function at all, because the matcher did not select it.

Limits to keep in mind

  • It runs in front of every matched request. That includes <Link> prefetches and requests for data. Anything slow here slows the whole site, so keep it to quick checks on headers, cookies and the URL.
  • Do not query a database here. Reading a cookie and verifying a signature is fine. Looking up a user or loading a permissions table is not what this layer is for. Authentication and Sessions shows how to do the cheap check in the proxy and the real check close to the data.
  • It cannot render React and it cannot call Server Actions or share a request-scoped cache with your pages.
  • Runtime. In Next.js 16, proxy.ts runs on the Node.js runtime and the Edge runtime is not available for it. Projects that still need Edge keep middleware.ts for now. Node.js and Edge Runtimes compares the two.
  • It is not a security boundary on its own. A real incident (a header that let requests skip middleware in some self-hosted setups, fixed in patched releases) shows why: a protected page must check access again where the data is read. That is the whole point of Authorization and Data Security.
  • One file per project. If you need several concerns, split the code into functions in separate modules and call them from the one proxy function.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happened to middleware.ts in Next.js 16?

    Version 16 renames the file to proxy.ts to make its role clearer. The behavior is the same idea, and middleware.ts still works for now but is deprecated.
  2. 2. What is the difference between NextResponse.redirect() and NextResponse.rewrite()?

    A redirect sends the browser to a new URL. A rewrite keeps the address bar as it is and renders a different route behind the scenes.
  3. 3. Why should you set a matcher?

    With no matcher, the function runs for all requests. A matcher limits the work to the paths you care about.
  4. 4. Which task is a bad fit for the proxy file?

    Every matched request waits for the proxy, so slow work belongs close to the data, in your data layer, not here.

Summary

  • The proxy file (proxy.ts in Next.js 16, middleware.ts before) runs before routes and answers with next(), redirect() or rewrite().
  • Use config.matcher to limit it to the paths you need. Values must be constants and follow path-to-regexp syntax.
  • Redirects change the visible URL, rewrites do not. Both are useful for gates, variants and friendly URLs.
  • You can add headers and cookies to the response, and pass extra request headers to your routes.
  • Keep it fast and simple. No heavy data work, no React, and one file per project.
  • Never rely on it as the only access check. Verify access again where data is read.

Next: Authentication and Sessions