Next.jsMedium
How do you handle headers in Route Handlers?
Read incoming headers with request.headers.get(name) or (await headers()).get(name) from next/headers (read-only). Set outgoing headers by passing a headers object to new Response()/Response.json(), or by calling response.headers.set() before returning.
Reading
request.headers.get("authorization")(await headers()).get("user-agent"): async since Next.js 15. The returnedHeadersis read-only.- Useful values:
authorization,content-type,accept-language,x-forwarded-for(client IP behind a proxy), and host-provided geo headers.
Writing
Response.json(data, { headers: { "Cache-Control": "no-store" } }).const res = NextResponse.json(data); res.headers.set("X-Request-Id", id).- Multiple values:
headers.append("Set-Cookie", ...); prefer the cookies API for cookies.
Common response headers
- Caching:
Cache-Control(public, s-maxage=60, stale-while-revalidate=300, orprivate, no-store). - CORS:
Access-Control-Allow-Origin,-Methods,-Headers. - Downloads:
Content-Disposition: attachment; filename="report.csv". - Security:
X-Content-Type-Options: nosniff,Content-Security-Policy. - Rate limiting:
Retry-After,X-RateLimit-Remaining.
Tips
- Site-wide headers belong in
headers()innext.config.tsor inproxy.ts, not repeated in every handler. - Reading headers makes the handler request-time, so it cannot be prerendered.
- Do not trust
x-forwarded-forunless your host sets it; it can be spoofed by clients.
Code example
tsx
1// app/api/report/route.ts2import { headers } from "next/headers";3import { buildCsv } from "@/lib/reports";45export async function GET(request: Request) {6 const auth = request.headers.get("authorization");7 if (auth !== `Bearer ${process.env.REPORT_TOKEN}`) {8 return Response.json({ error: "Unauthorized" }, { status: 401, headers: { "WWW-Authenticate": "Bearer" } });9 }1011 const lang = (await headers()).get("accept-language")?.split(",")[0] ?? "en";12 const csv = await buildCsv({ lang });1314 return new Response(csv, {15 headers: {16 "Content-Type": "text/csv; charset=utf-8",17 "Content-Disposition": 'attachment; filename="report.csv"',18 "Cache-Control": "private, no-store",19 "X-Report-Lang": lang,20 },21 });22}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.