How to get the Request headers in Next.js app router
By Flavio Copes
Learn how to read request headers in the Next.js app router using the headers() function from next/headers in a Server Component, then pass them to clients.
To read the request headers in the Next.js app router, use the headers() function from the next/headers package. You call it in a Server Component, and it gives you the headers of the incoming request.
import { headers } from 'next/headers'
export default function MyComponent() {
const headersList = headers()
const referer = headersList.get('referer')
return <div>Referer: {referer}</div>
}
headers() returns a read-only instance of the Web Headers API. You can’t modify it (to set headers, use middleware or the next/server package).
get() looks up one header by name. Names are case insensitive, so get('User-Agent') and get('user-agent') return the same value. If the header is not present, you get null back.
You can also loop over all the headers:
const headersList = headers()
for (const [key, value] of headersList.entries()) {
console.log(`${key}: ${value}`)
}
Where can you call headers()?
headers() works in Server Components, Server Actions, and Route Handlers.
It does not work in Client Components. The headers belong to the incoming request, and Client Components render in the browser, where that request data does not exist.
One thing to know: headers change on every request, so calling headers() opts the route into dynamic rendering. Next.js can no longer generate that page statically at build time. That’s expected, but it can surprise you if you thought the page was static.
How to pass headers to Client Components
For Client Components, read the header in a Server Component and pass the value down via props:
import { headers } from 'next/headers'
import ClientComponent from './ClientComponent'
export default function ServerComponent() {
const headersList = headers()
const userAgent = headersList.get('user-agent')
return <ClientComponent userAgent={userAgent} />
}
'use client'
export default function ClientComponent({ userAgent }) {
return <div>User Agent: {userAgent}</div>
}
Only pass the specific header values the client needs, not the entire headers object. This keeps the payload small and avoids leaking data you didn’t mean to expose.
Watch out for newer Next.js versions
Starting with Next.js 15, headers() returns a Promise, so you await it:
const headersList = await headers()
If you upgrade and see warnings about headers() being used synchronously, this is why. Add the await and the rest of the code stays the same.
Related posts about next: