RFC: unstable_setHeaders() API for App Router - Before Streaming Begins #89220
Answered
by
mvpcraft
diego-toress
asked this question in
App Router
ProblemMany of us migrating from Pages Router need to set response headers dynamically based on fetched data:
The current recommendation is Middleware, but:
Proposed SolutionWhat about an API that sets headers before streaming begins? // app/products/[id]/page.tsx
import { unstable_setHeaders } from 'next/headers';
export default async function ProductPage({ params }) {
const product = await getProduct(params.id);
// Set headers BEFORE the component renders/streams
unstable_setHeaders({
'Surrogate-Key': product.id,
'Cache-Control': `s-maxage=${product.cacheTime}`,
});
return <ProductDetails product={product} />;
}Questions for the Team
|
Answered by
mvpcraft
Jan 29, 2026
Replies: 1 comment
|
Based on the research, here are the current solutions for setting response headers in App Router: ✅ Working Solutions1. Use Route Handlers (API Routes)// app/api/product/[id]/route.ts
import { NextResponse } from 'next/server';
export async function GET(request: Request, { params }) {
const product = await getProduct(params.id);
return NextResponse.json(product, {
headers: {
'Surrogate-Key': product.id,
'Cache-Control': `s-maxage=${product.cacheTime}`,
},
});
}2. Use Middleware (when headers don't depend on fetched data)// middleware.ts
import { NextResponse } from 'next/server';
export function middleware(request) {
const response = NextResponse.next();
response.headers.set('X-Custom-Header', 'value');
return response;
}3. Use
|
0 replies
Answer selected by
diego-toress
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on the research, here are the current solutions for setting response headers in App Router:
✅ Working Solutions
1. Use Route Handlers (API Routes)
2. Use Middleware (when headers don't depend on fetched data)