Relevant source files
The following files were used as context for generating this wiki page:
Overview
Request Middleware and Cookie Parsing Execution Flow
The HandleCatchallMiddlewareRequest -> GetCookieParser process describes how Next.js catches incoming requests intended for middleware handling, validates them against defined route matchers and conditional rules (such as checking headers, cookies, or queries), and extracts request cookies dynamically when evaluating routing conditions.
This execution path begins inside NextNodeServer when a request flagged with metadata indicating a middleware invocation is intercepted. The server retrieves the middleware configuration, compiles or looks up its route matchers, evaluates any conditional has or missing rules—which may parse incoming request cookies on-demand—and prepares the environment to execute the middleware function.
Sources: packages/next/src/server/next-server.ts:1943-1952
Step-by-Step Execution Trace
1. Handling Catchall Middleware Requests
The entry point for this flow is handleCatchallMiddlewareRequest within NextNodeServer. When an HTTP request enters the Node server, it checks whether the middlewareInvoke request metadata flag is set. If the flag is absent, the handler returns false to let other route handlers process the request. Otherwise, it retrieves the active middleware item and normalizes the request pathname, taking into account any configured internationalization (i18n) segments and trailing slashes.
Sources: packages/next/src/server/next-server.ts:1943-1972
2. Retrieving Middleware Configuration
Next, getMiddleware is called to fetch the active middleware routing item from the server's middleware manifest or fallback node environment. It checks if a root middleware exists at ['/'], and if so, acquires its compiled route matcher functions.
Sources: packages/next/src/server/next-server.ts:1588-1612
3. Fetching Middleware Matchers
To determine whether the request path matches the middleware's configuration, getMiddlewareMatcher is invoked with the middleware manifest item. This function consults a weak cache (MiddlewareMatcherCache) to avoid recompiling regex patterns repeatedly for the same middleware info object. If a cached matcher is not found, it passes the configuration's matchers array to getMiddlewareRouteMatcher.
Sources: packages/next/src/server/next-server.ts:179-196
4. Executing Route Matching
getMiddlewareRouteMatcher returns a closure that evaluates incoming pathnames against an array of proxy matchers. For each matcher, it attempts to execute its compiled regular expression against the request pathname. If the path matches and the matcher specifies conditional rules via has or missing properties, execution proceeds to evaluate those constraints.
Sources: packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts:14-36
5. Evaluating Conditional Route Match Constraints
The matchHas function inspects additional constraints (has or missing) defined on the route matcher. It iterates over each constraint item, validating properties based on their declared type (such as header, cookie, query, or host).
Sources: packages/next/src/shared/lib/router/utils/prepare-destination.ts:48-60
6. Checking Cookie and Header Values
Inside hasMatch, when evaluating a constraint of type 'cookie', the code checks if a pre-parsed cookies object exists directly on the request. If cookies are not attached to the request object yet, it falls back to dynamically parsing them from request headers.
Sources: packages/next/src/shared/lib/router/utils/prepare-destination.ts:66-75
7. Parsing Request Cookies on Demand
If cookie values are required for conditional matching and are missing from the request object, getCookieParser is invoked with req.headers. It returns a curried parseCookie function which extracts the cookie header, safely handles single or multi-value cookie arrays, and invokes Next.js's compiled cookie parser utility to return a dictionary of parsed cookies.
Sources: packages/next/src/server/api-utils/get-cookie-parser.ts:8-21
Architectural Diagrams
Sequence Diagram
Sources: packages/next/src/server/next-server.ts:179-196, packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts:14-36, packages/next/src/shared/lib/router/utils/prepare-destination.ts:48-75, packages/next/src/server/api-utils/get-cookie-parser.ts:8-21
Flowchart
Sources: packages/next/src/server/next-server.ts:1943-1988, packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts:14-36, packages/next/src/shared/lib/router/utils/prepare-destination.ts:48-75, packages/next/src/server/api-utils/get-cookie-parser.ts:8-21
Key Observations
Important
Lazy Cookie Parsing: Cookies are not parsed preemptively for every incoming request. They are only parsed when a route matcher defines conditional has or missing rules relying on cookie values and those cookies are not already populated on the request object.
Tip
Matcher Caching: NextNodeServer utilizes a WeakMap (MiddlewareMatcherCache) indexed by middleware manifest items, preventing redundant compilation of route regex and condition matchers across requests.
- Cross-Module Boundaries: This flow bridges the core server execution logic (
next-server.ts), routing utilities (middleware-route-matcher.tsandprepare-destination.ts), and HTTP API helper utilities (get-cookie-parser.ts). - Error Resilience: Malformed URI components encountered during pathname decoding are safely caught and treated as non-fatal, allowing the matcher to fall back gracefully or skip matching without crashing the server process.
On This Page
OverviewRequest Middleware and Cookie Parsing Execution FlowStep-by-Step Execution Trace1. Handling Catchall Middleware Requests2. Retrieving Middleware Configuration3. Fetching Middleware Matchers4. Executing Route Matching5. Evaluating Conditional Route Match Constraints6. Checking Cookie and Header Values7. Parsing Request Cookies on DemandArchitectural DiagramsSequence DiagramFlowchartKey Observations