Next.js16 min read

Next.js Middleware Not Working? Check proxy.ts, the Matcher and Redirects

In Next.js 16 middleware is called proxy, and most failures are quiet: a file in the wrong folder is ignored without a message, and a matcher can skip the pages you meant to protect. This guide matches each symptom to its cause. Every case was reproduced in a test project on version 16.3.5.

Ali RehmanAli RehmanFreelance Web Developer
Published
A row of stainless steel subway turnstiles seen from the side
On this page 16 sections

The redirect never happens. The header is missing, and the console.log you added prints nothing. Or the opposite: after an upgrade, the build stops with an error about a proxy you never wrote.

The short answer: In Next.js 16, middleware is called proxy. The file must be named proxy.ts or proxy.js, sit next to the app folder (inside src if you have one) and export a function named proxy or a default function. Run next build and look for the line ƒ Proxy (Middleware) at the end of the route list. If it is missing, Next.js did not find the file, and it will not tell you. If it is there, the cause is the matcher, the redirect or the way a header is set.

Each case below was reproduced on 16 November 2026 with Next.js 16.3.5: one throwaway project, 13 builds and 52 recorded checks. The last section explains how the test worked and what it left out. Two results differ from what the documentation says, and both are pointed out. On version 15 and earlier the file is still middleware.ts; only version 16 was tested.

First, check whether the file runs at all

Before changing any logic, find out which problem you have: the file is not picked up, or it runs and does something other than you expect. Three checks separate the two.

  1. 1Run next build and read the route list it prints. When Next.js has picked up the file, the list ends with ƒ Proxy (Middleware). In the test that line was printed for every setup that worked and was missing for both setups where the file was ignored.
  2. 2Add console.log("proxy", request.nextUrl.pathname) as the first line of the function and request a page. The line appears in the terminal that runs the server, not in the browser console.
  3. 3Open the browser’s Network panel and click the page request. A redirect from the proxy shows status 307 and a Location header.
What you see
→ section: most likely cause

Never runs, and no error
  → 2: file is in the wrong folder

Build fails after upgrading to 16
  → 1 or 8: export name or runtime

Runs on some pages, not others
  → 3: the matcher misses them

Page has no styles or images
  → 4: proxy catches static files

ERR_TOO_MANY_REDIRECTS
  → 5: login page is protected too

Status 500 on a redirect
  → 5: relative address

Header or cookie is missing
  → 6: set on the wrong object

Runs twice, or before a click
  → 7: prefetch and static pages

Static export: never runs
  → 9: no server to run it

Tested on Next.js 16.3.5.

1. In Next.js 16 the file is proxy, not middleware

Version 16 renamed the feature. The upgrade guide says the file is now proxy.ts and the exported function is proxy. What the function can do has not changed: it receives the request and can redirect, rewrite, set headers or answer directly.

// src/proxy.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function proxy(request: NextRequest) {
  return NextResponse.next();
}

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

The old name still works for now. In the test, src/middleware.js with a function named middleware ran exactly as before, and the build printed a warning: “The "middleware" file convention is deprecated. Please use "proxy" instead.” So an old file is not the reason your code does not run on version 16. A half-finished rename is a different matter, because it stops the build:

  • Both files exist. The build ended with “Both middleware file … and proxy file … are detected” and named the proxy file as the one to keep. Delete the old file.
  • The file is renamed but the function is not. A proxy.js that still exported a function named middleware failed with “Proxy is missing expected function export name”. The message goes on to say what it wants: a default export or a function named proxy.

Next.js has a codemod that renames the file and the function. The build warning prints the command, and the codemods page lists it. The codemod was not run in this test, so read its diff before you commit.

# Commit your work first, then run:
npx @next/codemod@latest middleware-to-proxy .

Settings in next.config.js that had “middleware” in their name were renamed as well. The upgrade guide gives skipMiddlewareUrlNormalize, now skipProxyUrlNormalize, as the example.

2. The file is in the wrong folder

This is the quiet failure. The proxy reference says the file belongs at the same level as app or pages: in the project root, or inside src when the project has one.

Without a src folder
  proxy.ts
  app/

With a src folder
  src/proxy.ts
  src/app/

Ignored, with no message
  proxy.ts    (when src/app exists)
  src/app/proxy.ts

The test tried both wrong places in a project with a src folder: proxy.js in the project root, and proxy.js inside src/app. Both builds succeeded. Neither printed a warning, neither listed ƒ Proxy (Middleware), and no request went through the function. If that file was your login check, every protected page is open and nothing tells you.

To confirm, open a private browser window and request a protected address without logging in. Then move the file, rebuild and look for the proxy line in the build output.

A project can have only one proxy file. The Proxy guide suggests keeping the logic in separate modules and importing them into that one file. If your project sets pageExtensions, the file name must follow the same pattern, for example proxy.page.ts.

3. The matcher does not cover the address

With a matcher, the proxy runs only for addresses that match it, and every other request skips the function. The test requested eleven addresses against three matchers:

  • /about ran for /about only. It did not run for /about/team or for /blog/about. The reference page says /about also matches /about/team; on 16.3.5 it did not, on the running server or in Next.js’s own matcher test function.
  • /dashboard/:path* ran for /dashboard and for everything below it, including addresses that have no page.
  • /exact/:path ran for exactly one more segment: /exact/a, but not /exact and not /exact/a/b.
  • Matching is case-sensitive. /About did not run the proxy.

So a matcher of /admin protects one page. To cover a whole section, write /admin/:path*.

A railway track splitting into two at a set of points, with trees on both sides
A matcher works like a set of points: it decides which requests are sent through the proxy. This is a contextual stock photograph, not a diagram of the test project.

Two matcher mistakes stop the build, which at least makes them visible:

  • No leading slash. A matcher written as about failed with “invalid middleware config: source must start with /”.
  • A matcher taken from a variable. The reference page says values that are not constants are ignored. In the test, with the default Turbopack build, const paths = ["/about"] followed by matcher: paths failed the build: “matcher needs to be a static string or array of static strings or array of static objects.” Write the list directly inside the config object.

You can test a matcher without deploying. The package next/experimental/testing/server exports unstable_doesMiddlewareMatch, which takes a config and an address and returns true or false. In the test it agreed with the running server for all eleven addresses. It is experimental, and in 16.3.5 the function still has the old name.

4. No matcher: the proxy catches scripts, styles and images

Without a matcher, the proxy runs for every request. The reference page spells out what that includes: files under _next/static, image requests to _next/image and everything in the public folder.

The test used the most common pattern, a redirect to /login when there is no session cookie, with no matcher. The login page itself returned status 200. Its script, its stylesheet and its logo were each answered with a 307 redirect to /login. In the browser the page never became interactive and the image did not load. The same happened to robots.txt and to a route handler. One load of the login page sent 21 requests through the proxy, 8 of them for files under _next/static.

The documented fix is a negative matcher that leaves out those paths. With the pattern from the reference page, scripts, styles and robots.txt loaded without touching the proxy, and the login page worked. Two things it did not do:

  • It does not skip files in public. The logo was still redirected to /login. Adding image extensions to the pattern fixed that: in a third build the logo loaded and pages were still protected.
  • It skips everything under /api. The route handler answered with status 200 and never passed through the proxy. If the proxy was your only check, your API routes are open. The pattern is a prefix, so by the matcher test function a page at /apiary would be skipped as well.
export const config = {
  matcher: [
    // Pages only: skip API routes, build files,
    // metadata files and images in public/
    "/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
  ],
};

Add your own extensions if public holds fonts, PDFs or videos. When only the pictures are broken, the matcher is one of several possible causes; the guide to next/image errors in production covers the others.

5. The redirect loops or returns an error

The loop. The browser shows ERR_TOO_MANY_REDIRECTS when the login page is inside the area the proxy protects. The test protected /members/:path* and put the login page at /members/login. A request to a members page was redirected to the login page, which was redirected to itself, twelve times in a row until the test stopped following. The browser gave up with ERR_TOO_MANY_REDIRECTS. With the session cookie set, the same address loaded.

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const loggedIn = request.cookies.has("session");

  // Let the login page through first
  if (pathname === "/members/login") {
    return NextResponse.next();
  }
  if (!loggedIn) {
    const url = request.nextUrl.clone();
    url.pathname = "/members/login";
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}
A stainless steel ticket gate showing a green arrow that points left
A redirect only helps when the page it points to lets the visitor in. This is a contextual stock photograph, not a screenshot of the test project.

The error. NextResponse.redirect("/login") looks right and fails. The test got status 500, and the server log explained why: “URL is malformed "/login". Please use only absolute URLs”. Build the address from the request, as in the example above, or with new URL("/login", request.url). The error page for that message shows the same fix.

The status. A redirect from the proxy is a 307, a temporary redirect. For a permanent move that does not depend on the request, the Proxy guide recommends the redirects setting in next.config first. Those redirects are also applied before the proxy runs.

The wrong host. A common report is a redirect that sends visitors to localhost when the app runs behind another server. The test could not reproduce it on 16.3.5. For a redirect to the same site, the Location header was the path alone, /about, with no host in it. That held for new URL(path, request.url) and for request.nextUrl.clone(), and when the request carried a different Host or X-Forwarded-Host header. No real reverse proxy or container was part of the test.

NextResponse.next() accepts headers in two places, and they go in opposite directions.

const headers = new Headers(request.headers);
headers.set("x-tenant", "acme");

// To your page or route handler
return NextResponse.next({ request: { headers } });

// To the visitor's browser
return NextResponse.next({ headers });

In the test, the first form did what it should: the page read the header with headers(), a route handler read it from the request, and the browser did not receive it.

The second form sent the header to the browser, as the NextResponse reference says it will. On the Node.js server the page could read it too, because the router copies the proxy’s response headers onto the request. That makes the mistake easy to miss. Nothing looks broken, and a value meant for your own code is sent to every visitor. If the header holds a user ID, a role or an internal address, use the first form.

Cookies are set on the response: create it with NextResponse.next(), call response.cookies.set() and return that response. In the test the browser received the Set-Cookie header, and the page rendered in that same request already read the new value through cookies(). To read a cookie in the proxy, use request.cookies.get().

If the missing value comes from process.env, the proxy is probably not the cause. It reads server variables when the request arrives, like a route handler; the guide to environment variables that are undefined covers that side.

7. It runs more often than you expect

A proxy that works can still surprise you with how often it runs. Four results from the test:

  • Static pages. A page that was prerendered at build time still went through the proxy on every request.
  • Prefetching. Next.js prefetches links that are visible on the page. With two links on the home page, the proxy ran twice for each linked address before anyone clicked.
  • Server Functions. Submitting a form that calls a Server Function sent a POST to the page’s own address, and the proxy ran for it.
  • Missing pages. The proxy ran for matched addresses that ended in a 404.

This is why the documentation asks you to keep the function light. The authentication guide says to read the session from the cookie only and to avoid database checks there, because the proxy also runs on prefetched routes. The Proxy guide adds that the cache options of fetch have no effect inside it.

It also makes the proxy a poor place to count page views. The function cannot tell a prefetch from a visit: Next.js removes its internal headers, such as rsc and next-router-prefetch, from the request it passes in, and in the test both were empty. The reference page shows matcher conditions, has and missing, that can keep prefetch requests away from the proxy. Those conditions were not part of the test.

8. Edge runtime settings stop the build

Middleware used to run on the Edge runtime. Proxy runs on Node.js, and the reference page says this cannot be configured. A file that still carries the old setting does not build. In the test, export const runtime = "edge" in proxy.js failed with “Route segment config is not allowed in Proxy file … Proxy always runs on Node.js runtime.”

Remove the line. If you depend on the Edge runtime, the upgrade guide’s advice is to keep the file as middleware for now, and it says more instructions will follow in a later release.

9. Static export: the build passes and the proxy never runs

With output: "export", the build produces plain files for a static host. There is no server left to run a function before each request, and the static exports guide lists Proxy among the features that are not supported.

The build does not say so. In the test it succeeded without a warning, and its route list even showed ƒ Proxy (Middleware). The exported folder held the page as a static HTML file. The only hint came in development: next dev printed “Middleware cannot be used with "output: export"”, and the proxy did not run.

On a static host, redirects have to come from the host’s own redirect rules. A login check needs a server, either this app without the export setting or a separate API.

Do not make the proxy your only login check

The Proxy guide describes the proxy as a place for optimistic checks and says it should not be used as a full session management or authorization solution. The test shows why that is practical advice. A file in the wrong folder switched the check off without a message. The documented matcher left every API route outside it. And a matcher that misses one address misses the Server Functions on that page too.

Use the proxy to send visitors without a session to the login page early. Then check the session again where the data is read or changed: in the page, in each route handler and in each Server Function. The data security guide describes that pattern, and the authentication guide on this site explains what sessions and tokens protect.

Fixes that create new problems

  • Deleting the matcher so the proxy “runs everywhere”. It then also runs for scripts, styles and images, and a redirect breaks the page, as in section 4.
  • Passing all request headers back with NextResponse.next({ headers }). That sends them to the browser. Use the request form and pass only what your code needs.
  • Adding database or API calls to the proxy. They run on every matched request, including prefetches and static pages.
  • Keeping both files “while testing”. The build fails when middleware and proxy files exist together.
  • Hard-coding the domain in a redirect. Visitors on a preview or staging address are then sent to production. Build the address from request.url.
  • Excluding /api and forgetting it. If the matcher skips API routes, each route handler needs its own check.

Check the fix on a production build

  1. 1Build the app with next build. The route list should end with ƒ Proxy (Middleware).
  2. 2Start the result with next start, open a private window and request a protected address. You should land on the login page after one redirect.
  3. 3On the login page, open the Network panel. Scripts, styles and images should return 200, not 307.
  4. 4Request an API route directly, without logging in, and check that it refuses.
  5. 5Look at the response headers of a normal page for anything the proxy should not be sending.
  6. 6For the matcher, write a small test with unstable_doesMiddlewareMatch that lists the addresses that must and must not run.
# One redirect, then the login page
curl -sI https://example.com/dashboard
# Expect: 307 and location: /login

When to bring in a developer

Paying for help makes sense when the proxy sits in front of real accounts or payments and you cannot say for certain that every route is covered. The same goes for setups with an authentication library, internationalised routing or several domains, and for apps behind another proxy or CDN where redirects land in the wrong place. In those setups the cause is usually spread across the build output, the hosting configuration and the code.

Whoever looks at it will need the Next.js version, the location of the file, the matcher, the address that misbehaves and what the Network panel shows for it. Leave out session cookies and secrets. I take on this kind of work through my Next.js development service, and the contact page is where to send those details. Hiring someone else? The guide on how to hire a Next.js developer has the questions to ask first.

Frequently asked questions

Is middleware removed in Next.js 16?

No. It is deprecated and renamed to proxy. In the test on 16.3.5, a middleware.js file still ran and the build printed a deprecation warning. Rename the file and the function to proxy when you can, and never keep both files.

Where does proxy.ts go if I use a src folder?

Inside src, next to src/app. A proxy.ts in the project root of such a project, or inside the app folder, is ignored without any message.

Why does my proxy run on some routes and not others?

The matcher decides. A plain path such as /admin matched only that exact address in the test. Use /admin/:path* to include everything below it, and remember that matching is case-sensitive.

Why do I get ERR_TOO_MANY_REDIRECTS from my proxy?

The page you redirect to is itself redirected. Usually the login page is inside the protected matcher. Let the login page through before the session check, or keep it outside the matcher.

Can proxy.ts use the Edge runtime?

No. Proxy always runs on the Node.js runtime, and a runtime export in the file stops the build. The upgrade guide says to keep the file as middleware if you still need the Edge runtime.

Does the proxy run for static pages?

Yes, on a Node.js server. In the test a prerendered page went through the proxy on every request. With output: "export" it never runs, because there is no server.

Sources, test and review scope

The documented rules are taken from the Next.js proxy reference, the Proxy guide, the version 16 upgrade guide, the codemods page, the NextResponse reference and the guides to authentication, data security and static exports. The build error for a wrong export links to a message page about the rename. All of these pages were read on 16 November 2026. The quoted messages are the ones the test recorded.

The test project is a new App Router app with a src folder. It ran on Next.js 16.3.5 with React 19.2.4, the default Turbopack bundler and Node.js 24, and it was built 13 times; each build changed only the proxy or middleware file and, once, the output setting. Whether the function ran was read from a line it printed in the server’s terminal, responses were read without following redirects, and six steps used a real browser. Across 32 recorded steps, all 52 expectations matched, including these:

  1. 1With a src folder, proxy.js in the project root or inside src/app built without a message and never ran.
  2. 2src/middleware.js still ran, with a deprecation warning. Both files together, a function still named middleware in proxy.js and a runtime export each stopped the build.
  3. 3A matcher of /about did not run for /about/team. A matcher without a leading slash and a matcher taken from a variable stopped the build.
  4. 4Without a matcher, a login redirect also redirected the page’s script, stylesheet and logo. The documented negative matcher fixed the first two and skipped /api; adding image extensions fixed the logo.
  5. 5A login page inside the protected matcher redirected to itself until the browser stopped with ERR_TOO_MANY_REDIRECTS. A relative redirect address returned status 500.
  6. 6Headers in NextResponse.next({ request: { headers } }) reached the page and not the browser. Headers in NextResponse.next({ headers }) reached the browser.
  7. 7A static page, link prefetches and a Server Function call all went through the proxy.
  8. 8With output: "export", the build succeeded and listed the proxy; in development the proxy did not run and an error was printed.

What the test left out: it ran on a single Windows machine with the Node.js server, so Vercel and other hosts, a CDN or reverse proxy in front of the app, Docker, the Edge runtime, the Pages Router, internationalised routing, authentication libraries, webpack builds and versions before 16 were not covered. The codemod was not run. This guide was prepared with AI-assisted research and testing, and I checked the results against the linked sources before publishing.

Written by

Ali Rehman - Freelance Web Developer

I work on WordPress websites, practical fixes and scoped web applications. Read my background and skill scope, or send a project brief to discuss a written plan and quote - start here.

More articles by Ali Rehman →