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.
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025