Here’s how to retrieve request headers in Next.js (app router).
To access request headers, use the ‘headers’ function from the ‘next/headers’ package:
import { headers } from 'next/headers'
export default function MyComponent() {
const headersList = headers()
const referer = headersList.get('referer')
return <div>Referer: {referer}</div>
}
The ‘headers’ function is read-only (to set headers, use middleware or the ‘next/server’ package).
Note that this function only works in Server Components.
For client components, you need to pass the headers from a server component, for example 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>
}
Remember that you should only pass the specific header information needed by the client component, rather than the entire headers object, to maintain security and minimize data transfer.