Loading lessons...
Cookie & Session Management in Next.js
Cookie & Session Management in Next.js
Next.js provides the cookies() function from next/headers to read, write, and delete cookies securely in Server Components, Server Actions, and Route Handlers.
1. Reading Cookies in Server Components
// app/dashboard/page.tsx - React Server Component
import { cookies } from 'next/headers';
export default async function DashboardPage() {
const cookieStore = await cookies();
const theme = cookieStore.get('theme')?.value || 'light';
const userSession = cookieStore.get('session_id')?.value;
return (
<div className={`p-6 ${theme === 'dark' ? 'bg-slate-900 text-white' : 'bg-white'}`}>
<h1>User Dashboard</h1>
<p>Session ID: {userSession || 'Not Logged In'}</p>
</div>
);
}
2. Setting & Deleting Cookies in Server Actions
⚠️ DocHero Safety Disclaimer
Setting or deleting cookies using cookies() can only be performed inside Server Actions or Route Handlers. You cannot set cookies directly inside a rendering Server Component.
// app/actions/auth.ts
'use server';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
export async function loginAction(formData: FormData) {
const email = formData.get('email') as string;
// 1. Generate session token...
const token = 'xyz_sample_jwt_token_123';
// 2. Save secure HttpOnly cookie!
const cookieStore = await cookies();
cookieStore.set('session_token', token, {
httpOnly: true, // Prevents client-side JS access (XSS defense)
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24 * 7, // 1 week duration
});
redirect('/dashboard');
}
export async function logoutAction() {
const cookieStore = await cookies();
// Delete cookie!
cookieStore.delete('session_token');
redirect('/login');
}
Cookie API Methods Reference
| Method | Where Callable | Purpose |
|---|---|---|
cookieStore.get(name) | RSC, Actions, Route Handlers | Returns cookie object { name, value } |
cookieStore.getAll() | RSC, Actions, Route Handlers | Returns array of all incoming cookies |
cookieStore.has(name) | RSC, Actions, Route Handlers | Returns boolean if cookie exists |
cookieStore.set(name, val, opts) | Server Actions, Route Handlers | Sets HTTP cookie header |
cookieStore.delete(name) | Server Actions, Route Handlers | Deletes cookie by setting maxAge 0 |
TL;DR
- Import
cookiesfromnext/headers. - In Next.js 15+, call
const cookieStore = await cookies(). - Read cookies anywhere on the server using
cookieStore.get(name). - Mutate cookies (
set,delete) exclusively inside Server Actions or Route Handlers. - Always use
httpOnly: truefor authentication session tokens to prevent XSS attacks.