🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js Cookies and Headers

A cookie is a small piece of data the browser keeps and sends back with each request. The server reads it, and a Route Handler sets it.

The theme endpoint sets the cookie

The handler picks dark or light, then sets the shelf-theme cookie for 30 days.

export async function POST(request: Request) {
  const body = await request.json();
  const theme = body.theme === "dark" ? "dark" : "light";
  const response = NextResponse.json({ theme });
  response.cookies.set("shelf-theme", theme, {
    path: "/",
    maxAge: 60 * 60 * 24 * 30,
  });
  return response;
}

The cookie header, as sent

The check posts a dark theme and prints the cookie header. The cookie is set for 30 days.

curl -s -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d '{"theme":"dark"}' http://localhost:3112/api/theme | grep -i 'set-cookie'

The reader page reads the cookie

The check visits the reader page with the dark cookie. The theme reads dark.

curl -s -H 'Cookie: shelf-theme=dark' http://localhost:3112/reader | grep -o 'Your shelf theme is <!-- -->dark'

Example

curl -s -X POST -H 'Content-Type: application/json' -d '{"theme":"dark"}' http://localhost:3112/api/theme

Key points

  • Cookie: a small named value the browser stores and sends with each visit
  • The reader page reads the shelf-theme cookie. No cookie means light.
  • The theme endpoint sets the cookie. It answers with the theme and the cookie together.
  • A header carries the cookie. The Set-Cookie header sets it, and the Cookie header sends it back.
  • The cookie lasts 30 days. The path is the whole site.

In this example, the POST call sets the theme to dark. The answer is JSON with the theme, and the Set-Cookie header beside it sets shelf-theme to dark. The next visit sends that cookie back, and the reader page shows Your shelf theme is dark. With no cookie the same page shows light. The cookie carries the choice between visits.

Note

The expiry date in the header moves with the day the call runs. Your date will differ.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

Which header sets a cookie?