What is the next/headers module?

next/headers provides server-only functions for reading request data: cookies() to read and (in Server Functions and Route Handlers) write cookies, headers() to read request headers, and draftMode() to check or toggle Draft Mode. All three return Promises since Next.js 15 and must be awaited.

The functions

  • cookies(): get, getAll, has, and in Server Functions and Route Handlers also set, delete.
  • headers(): a read-only Headers object (get, has, entries).
  • draftMode(): isEnabled, enable(), disable() (toggle only in Route Handlers and Server Functions).

Where they work

Server Components, Server Functions, Route Handlers, generateMetadata, and other server code that runs during a request. Not in Client Components, and not at module scope.

Effect on rendering

They are request-time APIs:

  • Previous model: using them made the whole route dynamic.
  • Cache Components: the component using them is request-time and must be inside <Suspense>; the rest of the route stays in the static shell.
  • They cannot be called inside "use cache". Read outside and pass values as arguments, or use "use cache: private", which allows cookies() and headers().

Async since Next.js 15

const store = await cookies(). Synchronous access was a temporary compatibility mode in 15 and was removed in 16. The codemod npx @next/codemod@latest next-async-request-api . migrates old code.

Related

In Proxy, use request.cookies and request.headers instead. In Client Components, use document.cookie sparingly, or have the server pass values down.

Code example

tsx
1// app/dashboard/greeting.tsx (Server Component)
2import { cookies, headers, draftMode } from "next/headers";
3
4export async function Greeting() {
5 const cookieStore = await cookies();
6 const headerList = await headers();
7 const { isEnabled: isDraft } = await draftMode();
8
9 const name = cookieStore.get("name")?.value ?? "there";
10 const lang = headerList.get("accept-language")?.split(",")[0] ?? "en";
11
12 return (
13 <p>
14 {lang.startsWith("hi") ? "नमस्ते" : "Hello"} {name} {isDraft && "(draft)"}
15 </p>
16 );
17}
18
19// app/page.tsx
20// <Suspense fallback={<p>Hello</p>}><Greeting /></Suspense>
21
22// app/actions.ts - writing cookies is allowed here
23// "use server";
24// export async function setName(formData: FormData) {
25// (await cookies()).set("name", String(formData.get("name")), { path: "/", httpOnly: true });
26// }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app