Cookies in Server Actions

Read & Set Cookies on the Server

Cookies in Server Actions

`next/headers` exposes `cookies()` and `headers()`, both usable in Server Components and Server Actions. In Next.js 15 they are async.

4 min read Level 2/5 #nextjs#cookies#actions
What you'll learn
  • Read a cookie with `cookies().get`
  • Set a cookie with `cookies().set`
  • Delete with `cookies().delete`

Server-side cookies power auth tokens, theme preferences, feature flags, and anything else that needs to follow the user. next/headers is the API.

import { cookies } from 'next/headers'

export default async function Page() {
  const c = await cookies()
  const session = c.get('session')?.value
  if (!session) return <p>Not signed in</p>
  return <p>Hello, session {session.slice(0, 8)}...</p>
}

In Next.js 15 cookies() returns a promise — always await it.

You can only write cookies in a Server Action or Route Handler — not during a Server Component render. That is by design; rendering is supposed to be side-effect-free.

'use server'
import { cookies } from 'next/headers'

export async function setTheme(theme: 'light' | 'dark') {
  const c = await cookies()
  c.set('theme', theme, {
    httpOnly: false,    // readable by JS for the theme switch
    sameSite: 'lax',
    path: '/',
    maxAge: 60 * 60 * 24 * 365,
  })
}

Deleting

'use server'
import { cookies } from 'next/headers'

export async function signOut() {
  const c = await cookies()
  c.delete('session')
}

Auth Token Pattern

A classic flow: validate credentials in an action, set a session cookie with httpOnly: true, then redirect('/'). The cookie travels with every subsequent request, and any Server Component can read it to know who is signed in.

Error Handling in Actions →