Middleware Capabilities
Mutating requests, headers, and cookies.
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.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Middleware can rewrite URLs, which is invisible to the user (the URL bar doesn't change).
- Setting
res.headerssends headers to the browser. - Setting
request.headersinNextResponse.next()sends headers to Server Components. - You can also read and set cookies directly via
request.cookiesandres.cookies.
Done with this concept?
Mark it complete to track your progress. No login needed.