Middleware Capabilities

Mutating requests, headers, and cookies.

Next.js4 min readConcept 60 of 66

Beyond Redirects

Middleware is not just a bouncer at the door; it's a traffic manipulator.

While it is commonly used to redirect unauthenticated users to /login, it can also rewrite URLs (masking the true path from the user), read and set cookies, and inject custom headers into the request before it reaches your Server Components.

Passing Context Downstream

Imagine you verify a JWT token in Middleware to ensure the user is logged in. Your downstream page.tsx server component also needs to know *who* that user is to fetch their data.

Instead of verifying the token twice, Middleware can decode the token and attach x-user-id: 123 to the request headers.

When the request finally reaches your Server Component, it simply calls headers().get('x-user-id').

Implementation

typescript

import { NextResponse } from 'next/server';

import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {

// 1. Clone the request headers

const requestHeaders = new Headers(request.headers);

// 2. Inject a custom header

requestHeaders.set('x-user-id', '999');

// 3. Pass the mutated headers downstream

return NextResponse.next({

request: {

headers: requestHeaders,

},

});

}

Header Injection Lab

Watch how a JWT token is decoded at the Edge, injected as a custom header, and securely read by a downstream Server Component.

Client
Edge
Origin
GET /dashboard
Cookie: jwt=abc...
200 OK
// Request Lifecycle Log
Waiting for request...

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1How do you pass a custom header from Middleware down to a Server Component?

Remember this

  • Middleware can rewrite URLs, which is invisible to the user (the URL bar doesn't change).
  • Setting res.headers sends headers to the browser.
  • Setting request.headers in NextResponse.next() sends headers to Server Components.
  • You can also read and set cookies directly via request.cookies and res.cookies.

Done with this concept?

Mark it complete to track your progress. No login needed.