---
title: "Middleware Request Cookie Parsing"
description: "The HandleCatchallMiddlewareRequest -> GetCookieParser process describes how Next.js catches incoming requests intended for middleware handling, validates them against defined route matchers and co..."
last_updated: "2026-10-12T06:38:56.872063+00:00"
canonical_url: "https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/how-it-works/middleware-request-cookie-parsing"
---

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [packages/next/src/server/next-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts)
- [packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts)
- [packages/next/src/shared/lib/router/utils/prepare-destination.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/prepare-destination.ts)
- [packages/next/src/server/api-utils/get-cookie-parser.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/get-cookie-parser.ts)
</details>

## 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](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1943-L1952)

---

## 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](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1943-L1972)

### 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](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1588-L1612)

### 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](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L179-L196)

### 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](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts#L14-L36)

### 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](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/prepare-destination.ts#L48-L60)

### 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](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/prepare-destination.ts#L66-L75)

### 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](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/get-cookie-parser.ts#L8-L21)

---

## Architectural Diagrams

### Sequence Diagram

```mermaid
sequenceDiagram
    participant Server as NextNodeServer (next-server.ts)
    participant MatcherUtil as MiddlewareRouteMatcher (middleware-route-matcher.ts)
    participant PrepareDest as PrepareDestination (prepare-destination.ts)
    participant CookieParser as CookieParser (get-cookie-parser.ts)

    Server->>Server: handleCatchallMiddlewareRequest()
    Server->>Server: getMiddleware()
    Server->>Server: getMiddlewareMatcher()
    Server->>MatcherUtil: getMiddlewareRouteMatcher(matchers)
    MatcherUtil->>PrepareDest: matchHas(req, query, has, missing)
    
    alt type === 'cookie'
        PrepareDest->>CookieParser: getCookieParser(req.headers)
        CookieParser-->>PrepareDest: parseCookie() function
        PrepareDest->>PrepareDest: Extract cookie value
    end

    PrepareDest-->>MatcherUtil: returns match result (true/false)
    MatcherUtil-->>Server: returns boolean match status
```
Sources: [packages/next/src/server/next-server.ts:179-196](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L179-L196), [packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts:14-36](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts#L14-L36), [packages/next/src/shared/lib/router/utils/prepare-destination.ts:48-75](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/prepare-destination.ts#L48-L75), [packages/next/src/server/api-utils/get-cookie-parser.ts:8-21](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/get-cookie-parser.ts#L8-L21)

### Flowchart

```mermaid
flowchart TD
    A[Handle Request] --> B{Is Middleware Invoke?}
    B -- No --> C[Return false]
    B -- Yes --> D[Get Middleware & Matcher]
    D --> E[Evaluate Pathname Match]
    E --> F{Has match & conditional rules?}
    F -- No --> G[Finish / Skip]
    F -- Yes --> H[Evaluate matchHas]
    H --> I{Cookie Rule Present?}
    I -- No --> J[Match Success]
    I -- Yes --> K{Cookies on Request?}
    K -- Yes --> L[Read req.cookies]
    K -- No --> M[Call getCookieParser]
    M --> N[Parse Cookie Headers]
    N --> O[Check Condition Values]
    O --> P[Run Middleware Execution]
```
Sources: [packages/next/src/server/next-server.ts:1943-1988](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1943-L1988), [packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts:14-36](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts#L14-L36), [packages/next/src/shared/lib/router/utils/prepare-destination.ts:48-75](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/prepare-destination.ts#L48-L75), [packages/next/src/server/api-utils/get-cookie-parser.ts:8-21](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/get-cookie-parser.ts#L8-L21)

---

## 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.ts` and `prepare-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.

## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/llms.txt) for all pages in this wiki.
