Next.jsEasy
How do you access cookies in middleware?
Use request.cookies on the NextRequest to read incoming cookies (get, getAll, has), and response.cookies on a NextResponse to set or delete cookies on the response.
Reading
request.cookies.get("session")?.valuerequest.cookies.getAll()request.cookies.has("consent")
Writing
const res = NextResponse.next(); res.cookies.set("visited", "1", { path: "/", maxAge: 86400 })res.cookies.delete("old-cookie")- Works the same on
NextResponse.redirect()andNextResponse.rewrite()responses.
Passing a cookie to the app on the same request
Setting a cookie on the response only affects later requests. To make a new value visible to Server Components in this request, also set it on the request: request.cookies.set(...) and pass the modified headers via NextResponse.next({ request: { headers: request.headers } }).
Security
- Proxy can read a session cookie for an optimistic check, and even verify a signed JWT quickly. Do not perform database session lookups on every request here.
- Set
httpOnly,secureandsameSiteon sensitive cookies.
cookies() from next/headers
That API is for Server Components, Server Functions and Route Handlers. In Proxy, use the request and response objects.
Code example
tsx
1// proxy.ts2import { NextResponse, type NextRequest } from "next/server";34export function proxy(request: NextRequest) {5 const theme = request.cookies.get("theme")?.value ?? "light";6 const isFirstVisit = !request.cookies.has("visited");78 // Make a value available to Server Components in THIS request9 if (!request.cookies.has("visitor-id")) {10 request.cookies.set("visitor-id", crypto.randomUUID());11 }12 const response = NextResponse.next({ request: { headers: request.headers } });1314 // Persist cookies for future requests15 response.cookies.set("theme", theme, { path: "/", maxAge: 60 * 60 * 24 * 365 });16 response.cookies.set("visitor-id", request.cookies.get("visitor-id")!.value, {17 path: "/",18 httpOnly: true,19 sameSite: "lax",20 });21 if (isFirstVisit) response.cookies.set("visited", "1", { path: "/" });2223 return response;24}
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.