Server Components, Route Handlers, and Server Actions can read and set cookies and headers through async request APIs—powering auth sessions, locale, and caching behavior.
Reading cookies (App Router)
import { cookies } from 'next/headers';
export default async function Page() {
const session = (await cookies()).get('session');
return <p>Session: {session?.value ?? 'none'}</p>;
}
Setting cookies in Route Handlers / actions
import { cookies } from 'next/headers';
(await cookies()).set('theme', 'dark', { httpOnly: true, secure: true });
Dynamic rendering trigger
Using cookies() or headers() opts the route into dynamic rendering—Next.js cannot statically prerender personalized output.
Security defaults
httpOnlyfor session tokens (not readable by JS)securein production (HTTPS only)sameSiteto mitigate CSRF
Self-check
- Why do cookies force dynamic rendering?
- When should a cookie be httpOnly?