Read & Write Per Request
Cookies & Headers
The `cookies()` and `headers()` helpers from `next/headers` work in Server Components, Route Handlers, and Server Actions.
What you'll learn
- Read cookies and headers per request
- Write cookies from handlers and actions (only)
- Use `sameSite`, `httpOnly`, and `secure` correctly
cookies() and headers() are the canonical way to read request-specific data on the
server. Both are async in Next 15.
Reading
// app/dashboard/page.tsx
import { cookies, headers } from 'next/headers'
export default async function Page() {
const c = await cookies()
const h = await headers()
const token = c.get('token')?.value
const userAgent = h.get('user-agent')
return <p>Hi from {userAgent}</p>
} Calling either function forces the page to be dynamic — the result depends on the request.
Writing Cookies
You can only set cookies in places that own the response: Route Handlers and Server Actions. Server Components cannot write cookies because they have no response object.
// app/actions.ts
'use server'
import { cookies } from 'next/headers'
export async function login(form: FormData) {
const c = await cookies()
c.set('session', generateToken(), {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 7,
path: '/',
})
} Cookie Flags You Should Always Set
httpOnly: true— JS cannot read it; protects against XSS exfiltrationsecure: true— only sent over HTTPSsameSite: 'lax'— sensible CSRF defaultmaxAge— set an explicit expiry; do not rely on session cookies
headers() is read-only — set response headers via NextResponse.headers in Route
Handlers instead.