Next.jsMedium
How do you handle cookies in Route Handlers?
Read cookies with request.cookies.get(name) on a NextRequest, or with (await cookies()).get(name) from next/headers. Set or delete them with (await cookies()).set() / .delete(), or on a NextResponse with response.cookies.set().
Reading
request.cookies.get("session")?.valuerequest.cookies.getAll(),request.cookies.has("session")const store = await cookies(); store.get("theme").cookies()is async since Next.js 15 and synchronous access was removed in 16.
Writing
const store = await cookies(); store.set("session", token, options).store.delete("session")orstore.set("session", "", { maxAge: 0 }).- Or build a response:
const res = NextResponse.json(data); res.cookies.set(...).
Secure cookie options
httpOnly: trueso JavaScript cannot read session cookies (XSS protection).secure: trueso they are only sent over HTTPS.sameSite: "lax"(default and recommended) or"strict";"none"requiressecureand is only for cross-site use.path: "/", plusmaxAgeorexpires.- Consider the
__Host-prefix for session cookies (requiressecure,path=/, no domain).
Where cookies can be set
Route Handlers, Server Functions and Proxy. Not in Server Components during render, because headers are already being streamed. Reading cookies in a page makes that part request-time.
Effect on caching
Reading cookies in a GET handler means it cannot be prerendered. With Cache Components, cookies cannot be read inside "use cache"; read them outside and pass values as arguments.
Code example
tsx
1// app/api/session/route.ts2import { cookies } from "next/headers";3import { NextRequest } from "next/server";4import { createSession, getSessionUser } from "@/lib/session";56export async function GET(request: NextRequest) {7 const token = request.cookies.get("__Host-session")?.value;8 const user = token ? await getSessionUser(token) : null;9 return Response.json({ user });10}1112export async function POST(request: NextRequest) {13 const { userId } = await request.json(); // after verifying credentials14 const token = await createSession(userId);1516 (await cookies()).set("__Host-session", token, {17 httpOnly: true,18 secure: true,19 sameSite: "lax",20 path: "/",21 maxAge: 60 * 60 * 24 * 7, // 7 days22 });23 return Response.json({ ok: true });24}2526export async function DELETE() {27 (await cookies()).delete("__Host-session");28 return new Response(null, { status: 204 });29}
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.