The headers
function allows you to read the HTTP incoming request headers from a server component.
headers()
This API extends the Web Headers API. It is read-only, meaning you cannot set
/ delete
the outgoing request headers.
import { headers } from 'next/headers';
export default function Page() {
const headersList = headers();
const referer = headersList.get('referer');
return <div>Referer: {referer}</div>;
}
headers()
is a Dynamic Function whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into dynamic rendering at request time.const headersList = headers();
headers
does not take any parameters.
headers
returns a read-only Web Headers object.
Headers.entries()
: Returns an iterator
allowing to go through all key/value pairs contained in this object.Headers.forEach()
: Executes a provided function once for each key/value pair in this Headers
object.Headers.get()
: Returns a String
sequence of all the values of a header within a Headers
object with a given name.Headers.has()
: Returns a boolean stating whether a Headers
object contains a certain header.Headers.keys()
: Returns an iterator
allowing you to go through all keys of the key/value pairs contained in this object.Headers.values()
: Returns an iterator
allowing you to go through all values of the key/value pairs contained in this object.headers()
can be used in combination with Suspense for Data Fetching.
import { headers } from 'next/headers';
async function getUser() {
const headersInstance = headers()
const authorization = headersInstance.get('authorization')
// Forward the authorization header
const res = await fetch('...', {
headers: { authorization }
})
return res.json()
}
export default async function UserPage() {
const user = await getUser()
return <h1>{user.name}</h1>
}