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
headers()fromnext.config.tsredirects()fromnext.config.ts- Proxy (
proxy.ts): rewrites, redirects, headers, early responses beforeFilesrewrites fromnext.config.ts- File-system routes:
public/,_next/static/,pages/,app/ afterFilesrewrites- Dynamic routes such as
/blog/[slug] fallbackrewrites
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.ts2import type { NextConfig } from "next";34const 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 /old10 return [{ source: "/old", destination: "/new", permanent: true }];11 },12 async rewrites() {13 return {14 beforeFiles: [{ source: "/docs", destination: "/docs/intro" }], // step 415 afterFiles: [{ source: "/blog/:slug", destination: "/news/:slug" }], // step 616 fallback: [{ source: "/:path*", destination: "https://legacy.example.com/:path*" }], // step 817 };18 },19};2021export default nextConfig;2223// 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.