# Middleware Capabilities

> Mutating requests, headers, and cookies.

Subject: Next.js | Lesson 59 of 65 | 4 min read
Interactive lesson: https://codewithanimation.in/nextjs/middleware-capabilities
Previous: [Middleware](https://codewithanimation.in/nextjs/middleware.md) | Next: [Environment Variables](https://codewithanimation.in/nextjs/environment-variables.md)

## 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,
    },
  });
}
```

## Common mistake: The Request vs Response Trap

The most common mistake developers make is setting headers on the response object, expecting Server Components to see them.

If you do `const res = NextResponse.next(); res.headers.set('x-user-id', '999'); return res;`, the header is sent back to the **browser**.

Downstream Server Components read the *incoming request*, not the outgoing response. You must explicitly override the `request.headers` inside the `NextResponse.next()` configuration object.

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/nextjs/middleware-capabilities

## Check yourself

### Question 1

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

- A. By setting it on the NextResponse: res.headers.set('x-id', '1')
- B. By overriding the request headers inside NextResponse.next({ request: { headers } })
- C. By appending it to the URL query string.
- D. By exporting a global variable from middleware.ts.

Correct answer: B

Server Components read the incoming request. To modify what they see, you must intercept and clone the incoming request headers, mutate them, and explicitly pass them downstream via the `NextResponse.next()` options.

- Why not A: This sends the header back to the client browser, not to the Server Component.
- Why not C: While possible, this exposes the ID in the URL, which is messy and potentially insecure.
- Why not D: Edge functions are stateless across requests; you cannot use global variables to pass data.

## 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`.
