How to get the Request headers in Next.js app router
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.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.