Next.jsEasy
How do you read cookies on the server in the App Router?
Call const cookieStore = await cookies() from next/headers in a Server Component, Server Function or Route Handler, then use cookieStore.get("name")?.value, getAll() or has(). In Route Handlers you can also use request.cookies, and in Proxy only request.cookies.
Reading
(await cookies()).get("theme")?.value(await cookies()).getAll()returns[{ name, value }](await cookies()).has("session")
Writing (not in Server Components)
Setting cookies requires sending headers, which is not possible once a Server Component is streaming. Set or delete cookies in:
- Server Functions:
(await cookies()).set("theme", "dark") - Route Handlers:
cookies()orresponse.cookies.set() - Proxy:
response.cookies.set()
Setting a cookie in a Server Function also refreshes the current route's data.
Rendering impact
- Reading cookies is request-time. With Cache Components, wrap the reading component in
<Suspense>so the rest of the page is prerendered. - Do not read cookies at the top of the root layout unless you really need the whole app to be request-time.
- Inside
"use cache", cookies are not allowed; pass the value in as an argument, so the cache key includes it.
Security
Cookies are user input. Verify signed or encrypted session cookies instead of trusting raw values, and keep sensitive ones httpOnly.
Code example
tsx
1// app/settings/theme-label.tsx (Server Component)2import { cookies } from "next/headers";34export async function ThemeLabel() {5 const store = await cookies();6 const theme = store.get("theme")?.value ?? "system";7 const all = store.getAll().map((c) => c.name);8 return <p>Theme: {theme} (cookies: {all.join(", ")})</p>;9}1011// app/settings/page.tsx12import { Suspense } from "react";13import { setTheme } from "./actions";1415export default function Settings() {16 return (17 <main>18 <h1>Settings</h1>19 <Suspense fallback={<p>Theme: …</p>}>20 <ThemeLabel />21 </Suspense>22 <form action={setTheme}>23 <button name="theme" value="dark">Dark</button>24 <button name="theme" value="light">Light</button>25 </form>26 </main>27 );28}2930// app/settings/actions.ts31// "use server";32// export async function setTheme(fd: FormData) {33// (await cookies()).set("theme", String(fd.get("theme")), { path: "/", maxAge: 31536000 });34// }
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.