How to get the Request headers in Next.js app router
THE AHA STACK MASTERCLASS
Now open with 50% off launch discount!
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.
→ Get my Next.js (pages router) Handbook
I wrote 20 books to help you become a better developer:
- Astro Handbook
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- CSS Handbook
- Node.js Handbook