Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 72 ยท Mutations and Forms

Cookies and Headers

Read and set cookies in Next.js with cookies() and headers(): where writing is allowed, httpOnly and sameSite options, and why layouts that read cookies go dynamic.

Every HTTP request arrives with a small bundle of metadata: headers that describe the browser, the language, the content type, and cookies that the browser stored earlier and sends back on every visit. Almost every real feature, from a theme preference to a login, rests on reading or writing this metadata. Next.js gives you two functions for it: cookies() and headers(), both imported from next/headers.

This lesson shows how to read both, where you are allowed to write cookies (it is not everywhere, and the reason is worth understanding), which cookie options matter for security, and what reading the request does to caching. It builds on Server Actions and Route Handlers, because those are the two places where cookies can be set.

The real next/headers module only works inside a running Next.js server, which this site cannot run. Next.js code appears in read-only blocks. The runnable examples are plain Node.js stand-ins that implement the same cookie rules, so you can see what the browser and the server actually exchange.

Two functions, one request

Reading the request

cookies() Read cookies, and set them in actions and handlers.
headers() Read-only view of the request headers.

Both are async since Next.js 15, so you await them.

1 / 2

Reading cookies

cookies() returns an object with get, getAll and has. Because the function needs a real request, you await it:

TSX
// app/page.tsx
import { cookies } from 'next/headers';

export default async function Home() {
  const cookieStore = await cookies();
  const theme = cookieStore.get('theme')?.value ?? 'light';

  return <main data-theme={theme}>Current theme: {theme}</main>;
}

get('theme') returns an object like { name: 'theme', value: 'dark' }, or undefined when the cookie is missing, which is why the optional chain is there. getAll() returns every cookie as an array and has('theme') answers yes or no.

Reading a cookie has a consequence you already know from Static vs Dynamic Rendering: the route can no longer be prerendered, because the output depends on who is asking. That is fine for a dashboard. It is a problem for a root layout, where one cookie read turns every page on the site dynamic.

Reading headers

headers() gives you the standard Web Headers object, read-only:

TSX
// app/debug/page.tsx
import { headers } from 'next/headers';

export default async function Debug() {
  const headerList = await headers();
  const language = headerList.get('accept-language') ?? 'unknown';
  const agent = headerList.get('user-agent') ?? 'unknown';

  return (
    <dl>
      <dt>Language</dt>
      <dd>{language}</dd>
      <dt>Browser</dt>
      <dd>{agent}</dd>
    </dl>
  );
}

Header names are case-insensitive, so get('User-Agent') and get('user-agent') find the same value. Typical uses are the preferred language (see Internationalization), the visitor's IP behind a proxy (x-forwarded-for), or a request id that your proxy file added earlier.

There is no headers().set(). To change what you send back, use one of these:

  • a headers rule in next.config.ts for the same headers on many routes,
  • the proxy file, for headers that depend on the request,
  • the headers option of the Response you return from a Route Handler.
TypeScript
// app/api/time/route.ts
export async function GET() {
  return Response.json(
    { now: new Date().toISOString() },
    { headers: { 'Cache-Control': 'no-store' } },
  );
}

Setting cookies

A cookie is created by a response header named Set-Cookie. HTTP sends all headers before the body, and a page streams its body while it renders. Once the first bytes of HTML have left the server, it is too late to add a header. That is the reason Next.js lets you set cookies only where the response has not started: in Server Actions and Route Handlers.

TypeScript
// app/actions.ts
'use server';

import { cookies } from 'next/headers';

export async function saveTheme(formData: FormData) {
  const theme = formData.get('theme') === 'dark' ? 'dark' : 'light';
  const cookieStore = await cookies();

  cookieStore.set('theme', theme, {
    path: '/',
    maxAge: 60 * 60 * 24 * 365, // one year, in seconds
    sameSite: 'lax',
  });
}

Notice that the action validates the value before storing it. Cookie values come from the client, so they are input like any other (see Validating Input).

You can also call cookieStore.set({ name, value, ...options }) with a single object, and cookieStore.delete('theme') to remove a cookie. Trying to call set or delete while a page renders throws an error that tells you cookies can only be modified in an action or a handler.

In a Route Handler you may use the same cookies() function, or build the header yourself on the Response. After a Server Action changes a cookie, Next.js re-renders the current page with the new value, so a form that saves the theme updates the screen in the same round trip.

The options you pass decide who can read the cookie and when the browser sends it.

Option What it does Use it for
httpOnly: true Hides the cookie from document.cookie Anything secret, such as a session id
secure: true Sends it only over HTTPS Everything in production
sameSite: 'lax' Not sent on cross-site POSTs or subrequests, but sent when a user follows a link to your site A sensible default
sameSite: 'strict' Never sent on cross-site requests, even link clicks Sensitive, rarely-linked areas
sameSite: 'none' Sent on every cross-site request (requires secure) Embedded widgets that need it
maxAge / expires Lifetime. Without either it is a session cookie that ends with the browser session Remember-me, preferences
path URL prefix where it is sent. / means everywhere Almost always /
domain Also send to subdomains. Leave it out to keep the cookie host-only Rarely needed

Two practical points. First, a cookie holding a login must be httpOnly, secure and sameSite: 'lax' at least: a script injected into your page can then not steal it, and other websites cannot ride on it. Second, a cookie is limited to about 4 KB and is sent on every request to your domain, including images, so store small identifiers and keep the data on the server.

A name that starts with __Host- adds a browser-enforced guard: the cookie must be Secure, have Path=/ and no Domain. It is a good habit for session cookies.

What the server and browser actually exchange

The request carries one Cookie header, with all cookies in a single line: theme=dark; lang=en. The response carries one Set-Cookie header per cookie, each with its options. The first example parses the first format and writes the second, and then runs a store that follows the same rule as Next.js: reading always works, writing only works in the right place.

Node.js Parse, serialize and guard cookies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at what the output teaches. The browser sent theme twice and the first one wins, which is how most servers read duplicates. Ana%20Garc%C3%ADa is decoded to a normal name, and the missing cookie gives undefined, not an error. Writing during rendering fails with a clear message, while the action produces one Set-Cookie line per change. Deleting a cookie is nothing special: the server sends the same name with Max-Age=0, and the browser throws the old cookie away.

What the browser does with those options

Cookie options are rules that the browser enforces, not your server. The second example is a tiny browser. Give it Set-Cookie lines and it answers two questions: which cookies can a script read through document.cookie, and which cookies travel along with a request. Compare a request that comes from your own site with one that a different site triggers.

Node.js What a browser does with each option

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The table of results is the practical lesson. A forged form on another site does not carry your session cookie, because Lax keeps it away from cross-site POSTs. That is a large part of the protection Server Actions rely on. Over plain http, the Secure cookies are not sent at all. This simulation is simplified: browsers also compare registrable domains and have extra rules for None and for third-party cookie blocking, but the three SameSite values behave as shown.

Reading cookies in layouts

You can call cookies() in a layout, and teams often do it to pick a theme or read a locale. Two cautions apply.

  1. The whole subtree becomes dynamic. Every page below that layout is rendered per request. Prefer reading the cookie in a small component, or apply the preference in the browser.
  2. Layouts are not re-rendered on every navigation. When a user moves between sibling pages, the layout stays mounted (see Inside the RSC Payload). A cookie changed by an action will refresh it, but a cookie changed some other way may not be reflected in the layout until a full reload. So never make security decisions in a layout. Authorization and Data Security explains the right place for those checks.

Cookies are not a database

Cookie values are visible to the user and can be edited with the browser's developer tools. Treat them as untrusted input. A preference like theme=dark is harmless, but a cookie that says role=admin is a bug waiting to happen, unless it is protected by a signature or replaced by an opaque session id that you look up on the server. That is the subject of Authentication and Sessions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where can you call cookieStore.set() in a Next.js app?

    Set-Cookie is a response header and a page streams its body while rendering, so it is too late to add headers by then. Actions and handlers run before a response is sent.
  2. 2. What does httpOnly: true do?

    HttpOnly keeps the cookie out of reach of scripts, so an injected script cannot steal a session id. Secure and SameSite are separate options.
  3. 3. A root layout calls await cookies() to read the theme. What is the main side effect?

    Reading the request in a layout makes each page beneath it render per request, which turns an otherwise static site dynamic.
  4. 4. How does a server remove a cookie from the browser?

    Deleting is just another Set-Cookie. An expired cookie is discarded, which is what cookieStore.delete() produces.
  5. 5. Which header lets a Route Handler tell the browser not to cache a JSON response?

    headers() is read-only. Response headers are set on the Response you return, in next.config.ts, or in the proxy file.

Summary

  • cookies() and headers() come from next/headers, are asynchronous, and make a route dynamic because they need a real request.
  • headers() is read-only. Set response headers on a Response, in next.config.ts or in the proxy file.
  • Cookies can be written only in Server Actions and Route Handlers, because Set-Cookie must be sent before the body.
  • Use httpOnly, secure and sameSite: 'lax' for anything sensitive, and keep cookies small.
  • The browser enforces cookie options. Deleting means sending the same name with Max-Age=0.
  • Cookie values are client input: validate them, and never trust a cookie that says what a user is allowed to do.
  • Do not read cookies in a root layout unless you accept a fully dynamic site, and never make security decisions there.

Next: Middleware and the Proxy File