← Back to Guides

Modifying request headers

Learn how to modify request headers in your Edge Middleware.

The following example shows how to modify request headers in your Edge Middleware.

Your middleware file should be placed at the root of your project. If you are using the src directory, the file should be placed in the src directory.

middleware.ts
import { NextResponse } from 'next/server';
 
export function middleware(request: Request) {
  // Clone the request headers
  // You can modify them with headers API: https://developer.mozilla.org/en-US/docs/Web/API/Headers
  const requestHeaders = new Headers(request.headers);
 
  // Add new request headers
  requestHeaders.set('x-hello-from-middleware1', 'hello');
  requestHeaders.set('x-hello-from-middleware2', 'world!');
 
  // Update an existing request header
  requestHeaders.set('user-agent', 'New User Agent overriden by middleware!');
 
  // Delete an existing request header
  requestHeaders.delete('x-from-client');
 
  // You can also set request headers in NextResponse.rewrite
  return NextResponse.next({
    request: {
      // New request headers
      headers: requestHeaders,
    },
  });
}
Last updated on June 21, 2024