Next.jsMedium

What is the execution order of middleware?

For each request, Next.js applies headers from next.config, then redirects from next.config, then Proxy (middleware), then beforeFiles rewrites, then file-system routes (public/, _next/static, app/, pages/), then afterFiles rewrites, then dynamic routes, and finally fallback rewrites.

The full order

  1. headers() from next.config.ts
  2. redirects() from next.config.ts
  3. Proxy (proxy.ts): rewrites, redirects, headers, early responses
  4. beforeFiles rewrites from next.config.ts
  5. File-system routes: public/, _next/static/, pages/, app/
  6. afterFiles rewrites
  7. Dynamic routes such as /blog/[slug]
  8. fallback rewrites

What this means in practice

  • A config redirect runs before Proxy, so Proxy never sees requests that a config redirect already handled.
  • Proxy runs before any page or Route Handler, which is why it can rewrite to them.
  • Headers from config are applied even if Proxy rewrites the request.
  • Only one Proxy file runs; there is no chain of middleware files. Compose functions inside it.
  • Server Functions are not separate routes: they are POSTs to the page, so they pass through Proxy for that page's path.

Inside the app after routing

Once a route matches: root layout, nested layouts, then the page render. Route segment config (ensureStatic, instant) and data caching apply at that stage, not in Proxy.

Debugging the order

next build --debug prints the configured rewrites, redirects and headers.

Code example

tsx
1// next.config.ts
2import type { NextConfig } from "next";
3
4const nextConfig: NextConfig = {
5 async headers() {
6 return [{ source: "/:path*", headers: [{ key: "x-step", value: "1-config-headers" }] }];
7 },
8 async redirects() {
9 // Step 2: runs before proxy.ts ever sees /old
10 return [{ source: "/old", destination: "/new", permanent: true }];
11 },
12 async rewrites() {
13 return {
14 beforeFiles: [{ source: "/docs", destination: "/docs/intro" }], // step 4
15 afterFiles: [{ source: "/blog/:slug", destination: "/news/:slug" }], // step 6
16 fallback: [{ source: "/:path*", destination: "https://legacy.example.com/:path*" }], // step 8
17 };
18 },
19};
20
21export default nextConfig;
22
23// proxy.ts runs at step 3, between config redirects and beforeFiles rewrites

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app