How to get the Request headers in Next.js app router

By

Learn how to read request headers in the Next.js app router with await headers() from next/headers in a Server Component, then pass values 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, await it, and it gives you the headers of the incoming request.

import { headers } from 'next/headers'

export default async function MyComponent() {
  const headersList = await headers()
  const referer = headersList.get('referer')
  
  return <div>Referer: {referer}</div>
}

Since Next.js 15, headers() returns a Promise, so you need await. The same pattern still applies on current Next.js 16 releases.

headers() resolves to 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 = await 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 async function ServerComponent() {
  const headersList = await 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.

Older Next.js versions

On Next.js 14 and earlier, headers() was synchronous:

const headersList = headers()

If you upgrade from that era and see warnings about headers() being used synchronously, add the await and make the Server Component async. The rest of the code stays the same.

Tagged: Next.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about next: