Q69: How do you forward custom context headers from Middleware into Server Components and Server Actions?
Edge Middleware cannot pass JavaScript object variables directly to down-stream Server Components. To communicate context (such as verified user IDs or geo-location tags), Middleware mutates request headers via request.headers.set('x-user-id', userId). Server Components and Actions read these headers using headers().
Header Injection and Retrieval Pattern
// 1. middleware.js
export function middleware(req) {
const reqHeaders = new Headers(req.headers);
reqHeaders.set('x-geo-country', req.geo?.country || 'US');
return NextResponse.next({ request: { headers: reqHeaders } });
}
// 2. app/page.js (Server Component)
import { headers } from 'next/headers';
export default async function Page() {
const headerList = await headers();
const country = headerList.get('x-geo-country');
return <p>User Country Context: {country}</p>;
}💡 Middleware injects custom x-geo-country headers into request context, consumed natively inside Server Components.
Key Takeaways
- Mutate request headers inside Middleware using
requestHeaders.set().bias - Read custom context headers inside Server Components/Actions via
headers().get('x-user-id').
Knowledge Check
How can Next.js Middleware pass request contextual information to down-stream Server Components?