Skip to content
BackendChapter 21 / 34Intermediate5 min read

Cookies & Headers

Read Next.js cookies and headers with await cookies() and await headers(), and set cookies in Server Actions, following the Next.js 16 async rules.

On this page

1. What are cookies and headers?

A cookie is a small piece of data that the browser sends with every request, like a session token or a theme. A header is extra information about the request, like user-agent, accept-language or referer.

In Next.js 16 both functions are async. You must write await cookies() and await headers(). The old synchronous access has been removed.

2. Why does it matter?

The server needs to know which user a request belongs to and where it came from. All of that lives in cookies and headers.

Client side cookie handlingnext/headers on the server
Reading the token with document.cookieawait cookies on the server
JavaScript can steal the tokenAn httpOnly cookie is hidden from JS
Parsing code everywhereReady made get, set, has, delete methods
Language detected in the browseraccept-language header on the server

3. Where is it used?

Use caseWhat is used
Login sessionAn httpOnly session cookie
Theme preferenceA theme cookie, read in a Server Component
Language detectionThe accept-language header
Analytics or loggingThe user-agent and x-forwarded-for headers
Webhook verificationA signature header in a Route Handler

4. How does it work?

From request to cookies
Browser request + cookies + headers
Next.js server
await cookies or await headers
A Server Component reads
A Server Action or Route Handler sets or deletes
Set-Cookie header in the response
WhereReadSet or delete
Server ComponentYesNo
Server ActionYesYes
Route HandlerYesYes
proxy.tsrequest.cookiesresponse.cookies

headers() is always read-only. To change response headers, set them with the Response in a Route Handler or in proxy.ts.

5. Code example

Example 1: reading in a Server Component

tsx
import { Suspense } from "react";
import { cookies, headers } from "next/headers";

async function Greeting() {
  const cookieStore = await cookies();
  const headerList = await headers();

  const theme = cookieStore.get("theme")?.value ?? "light";
  const language = headerList.get("accept-language")?.split(",")[0] ?? "en";

  return (
    <p>
      Theme: {theme}, Language: {language}
    </p>
  );
}

export default function Page() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <Greeting />
    </Suspense>
  );
}
ts
"use server";

import { cookies } from "next/headers";

export async function setTheme(theme: "light" | "dark") {
  const cookieStore = await cookies();
  cookieStore.set("theme", theme, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 365,
  });
}

export async function clearTheme() {
  const cookieStore = await cookies();
  cookieStore.delete("theme");
}

How does the code work?

PartMeaning
await cookies()The store of the request's cookies, async in Next.js 16
cookieStore.get("theme")?.valueThe value of the cookie, or undefined
await headers()Read-only request headers
<Suspense>This is runtime data, so it streams in with Cache Components
httpOnly: trueBrowser JavaScript cannot read the cookie
sameSite: "lax"Protects against CSRF on cross-site requests
maxAgeThe lifetime in seconds, here one year

Interview tip

"Why can't you set a cookie in a Server Component?" Answer: a cookie is a response header, and by the time a Server Component renders, the response has already started streaming. That is why setting happens in a Server Action or a Route Handler.

6. Common mistakes

Mistake: Using cookies without await

Why? In Next.js 16, cookies returns a Promise, and calling get directly gives an error.

Better: Always write const cookieStore = await cookies(), then call get or set.

Mistake: Setting a cookie inside a Server Component

Why? Response headers cannot be changed during render, and Next.js throws an error.

Better: Set or delete cookies in a Server Action or a Route Handler.

Mistake: Keeping the session token without httpOnly

Why? In an XSS attack, JavaScript can steal the token.

Better: Always set session cookies with httpOnly, secure and sameSite.

Mistake: Reading cookies in a function that uses use cache

Why? A cached result is shared between all users, so runtime data is not allowed there.

Better: Read the cookie value outside and pass it to the cached function as an argument.

7. What to learn before and after

Final quick revision

PointDetail
Importimport { cookies, headers } from "next/headers"
Asyncawait cookies(), await headers()
ReadServer Components, Actions, Route Handlers
Write cookiesOnly Server Actions and Route Handlers
HeadersRead-only
Secure cookiehttpOnly, secure, sameSite