Skip to content

Remembering with Cookies

The Course
•
20 min study

A theme, a language, whether someone is signed in: some things must be known on the server, before the page is built, so the page arrives right the first time. A cookie is a small value the browser stores and sends with matching requests, according to the cookie's domain, path and security rules.

A theme that sticks Next.js · 5 files
import Link from "next/link"; import { cookies } from "next/headers"; import "./globals.css"; export default async function RootLayout({ children }) { // Read on the server, on every request: the page arrives already themed. const cookieStore = await cookies(); const theme = cookieStore.get("theme")?.value ?? "light"; return ( <html lang="en"> <body data-theme={theme}> <header> <nav> <Link href="/">Home</Link> <Link href="/settings">Settings</Link> </nav> </header> {children} </body> </html> ); } export default function HomePage() { return ( <main> <h1>Home</h1> <p>Change the theme in Settings. It's remembered on every page.</p> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } body[data-theme="dark"] { background: #16202a; color: #e6edf3; } body[data-theme="dark"] a { color: #7cc7e8; } "use server"; import { cookies } from "next/headers"; export async function saveTheme(formData) { const theme = formData.get("theme") === "dark" ? "dark" : "light"; const cookieStore = await cookies(); cookieStore.set("theme", theme, { maxAge: 60 * 60 * 24 * 365 }); } import { cookies } from "next/headers"; import { saveTheme } from "./actions.js"; export default async function SettingsPage() { const theme = (await cookies()).get("theme")?.value ?? "light"; return ( <main> <h1>Settings</h1> <p>Theme: {theme}</p> <form action={saveTheme}> <button name="theme" value="light">Light</button>{" "} <button name="theme" value="dark">Dark</button> </form> </main> ); }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.

Go to Settings, press Dark, then go Home and press Reload in the address bar.

Setting it

JavaScript
"use server";

import { cookies } from "next/headers";

export async function saveTheme(formData) {
  const theme = formData.get("theme") === "dark" ? "dark" : "light";
  const cookieStore = await cookies();
  cookieStore.set("theme", theme, { maxAge: 60 * 60 * 24 * 365 });
}

A server action can set cookies. maxAge is in seconds: this one lasts a year. Without it, this is a session cookie. Browsers may restore session cookies when restoring a previous session, so closing a browser isn't a reliable way to clear one. The action accepts only "dark" or "light": a form can send anything.

The form uses two buttons with the same name and different values. The one you press is the one sent:

JSX
<form action={saveTheme}>
  <button name="theme" value="light">Light</button>{" "}
  <button name="theme" value="dark">Dark</button>
</form>

Reading it

JavaScript
const cookieStore = await cookies();
const theme = cookieStore.get("theme")?.value ?? "light";

The root layout reads it on the server and puts it on <body data-theme="dark">. The CSS does the rest. Because the server knows the theme before it builds the page, there's no flash of the wrong theme while the page loads, which a theme stored in localStorage and read in an effect can't avoid:

JSX
export default async function RootLayout({ children }) {
  // Read on the server, on every request: the page arrives already themed.
  const cookieStore = await cookies();
  const theme = cookieStore.get("theme")?.value ?? "light";

  return (
    <html lang="en">
      <body data-theme={theme}>
        <header>
          <nav>
            <Link href="/">Home</Link>
            <Link href="/settings">Settings</Link>
          </nav>
        </header>
        {children}
      </body>
    </html>
  );
}

After the action sets a cookie, Next.js renders the page again with the new value, so the change shows at once.

Cookies make a page dynamic

A page that reads cookies depends on who's asking, so it can't be built once in advance for everyone. Next.js notices, and builds it on every request, with no export const dynamic needed.

Not for secrets

Readers can see and change their own cookies in the browser's developer tools. A theme is fine. Signing someone in needs a cookie the server can check hasn't been forged, which sign-in libraries handle for you.

Exercise

Sepia

Add a third theme, Sepia: a warm background (#f4ecd8) with brown text (#5b4636).

Your working space Next.js · 5 files
import Link from "next/link"; import { cookies } from "next/headers"; import "./globals.css"; export default async function RootLayout({ children }) { // Read on the server, on every request: the page arrives already themed. const cookieStore = await cookies(); const theme = cookieStore.get("theme")?.value ?? "light"; return ( <html lang="en"> <body data-theme={theme}> <header> <nav> <Link href="/">Home</Link> <Link href="/settings">Settings</Link> </nav> </header> {children} </body> </html> ); } export default function HomePage() { return ( <main> <h1>Home</h1> <p>Change the theme in Settings. It's remembered on every page.</p> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } body[data-theme="dark"] { background: #16202a; color: #e6edf3; } body[data-theme="dark"] a { color: #7cc7e8; } "use server"; import { cookies } from "next/headers"; export async function saveTheme(formData) { const theme = formData.get("theme") === "dark" ? "dark" : "light"; const cookieStore = await cookies(); cookieStore.set("theme", theme, { maxAge: 60 * 60 * 24 * 365 }); } import { cookies } from "next/headers"; import { saveTheme } from "./actions.js"; export default async function SettingsPage() { const theme = (await cookies()).get("theme")?.value ?? "light"; return ( <main> <h1>Settings</h1> <p>Theme: {theme}</p> <form action={saveTheme}> <button name="theme" value="light">Light</button>{" "} <button name="theme" value="dark">Dark</button> </form> </main> ); }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

Adding a valid choice means updating what the form offers, what the server accepts, and how the page displays it.

Hint 2: a first step

Three places: a button in the settings page, the list of allowed values in the action, and a body[data-theme="sepia"] rule in globals.css.

Show one solution

In actions.js:

JavaScript
const choice = formData.get("theme");
const theme = ["light", "dark", "sepia"].includes(choice) ? choice : "light";

In settings/page.jsx:

JSX
<button name="theme" value="sepia">Sepia</button>

In globals.css:

CSS
body[data-theme="sepia"] {
  background: #f4ecd8;
  color: #5b4636;
}

The allowlist in the action is the real check: a form can send any value, and the server turns anything it doesn't know into light. So Sepia works only once the action accepts it. The button just offers it, and the CSS rule shows it. Skip the action change and pressing Sepia quietly gives you light.

Was this article helpful?

Your response is saved on this device.