Next.js cookies() Must Be Called in a Server Component— Fixed [2026]
Also covers: cookies() not a function · set cookie in App Router · cookie in Client Component
⚡ Quick Fix — Read in Server, Pass as Prop
// ✅ Server Component — can use cookies()
import { cookies } from 'next/headers'
import DashboardClient from './DashboardClient'
export default function DashboardPage() {
const cookieStore = cookies()
const token = cookieStore.get('auth-token')?.value
const theme = cookieStore.get('theme')?.value ?? 'light'
// Pass values as props to Client Component
return <DashboardClient token={token} theme={theme} />
}Why cookies() Only Works in Server Components
Error: cookies() was called outside a request scope.
cookies() should be called in a Server Component, Server Action, or Route Handler.
# or:
Error: You're importing a component that imports next/headers.
It only works in a React Server Component but one of its parents is marked with "use client".The cookies() function from next/headers reads the HTTP request headers which only exist on the server during a request. Client Components run in the browser after the page loads — there is no HTTP request available at that point. This is an intentional security boundary.
| Where | Read cookies | Set cookies |
|---|---|---|
| Server Component | cookies().get(name) | ❌ Not allowed |
| Server Action | cookies().get(name) | cookies().set(name, value) |
| Route Handler (GET/POST) | cookies().get(name) | cookies().set(name, value) |
| Middleware | request.cookies.get(name) | response.cookies.set(name, value) |
| Client Component | ❌ Cannot use cookies() | document.cookie (not recommended) |
Read Cookies in a Server Component
Correct pattern — Server Component onlyimport { cookies } from 'next/headers'
// ✅ Server Component — no 'use client'
export default async function ProfilePage() {
const cookieStore = cookies()
// Read a single cookie
const sessionId = cookieStore.get('session-id')?.value
// Read with fallback
const language = cookieStore.get('lang')?.value ?? 'en'
// Check if cookie exists
const isLoggedIn = cookieStore.has('auth-token')
// Get all cookies
const allCookies = cookieStore.getAll()
if (!isLoggedIn) {
redirect('/login')
}
return <div>Welcome back! Session: {sessionId}</div>
}Pass Cookie Values as Props to Client Components
The correct way to use cookie data in Client ComponentsClient Components cannot call cookies() but they can receive cookie values as props from a parent Server Component.
import { cookies } from 'next/headers'
import ThemeToggle from '@/components/ThemeToggle' // Client Component
export default function SettingsPage() {
const cookieStore = cookies()
const theme = cookieStore.get('theme')?.value ?? 'light'
const userId = cookieStore.get('user-id')?.value
return (
<div>
<h1>Settings</h1>
{/* Pass cookie values as regular props */}
<ThemeToggle initialTheme={theme} userId={userId} />
</div>
)
}'use client'
import { useState } from 'react'
export default function ThemeToggle({ initialTheme, userId }) {
const [theme, setTheme] = useState(initialTheme)
async function toggleTheme() {
const newTheme = theme === 'light' ? 'dark' : 'light'
// Call a Server Action to persist the cookie
await updateThemeCookie(newTheme)
setTheme(newTheme)
}
return <button onClick={toggleTheme}>Theme: {theme}</button>
}Set and Delete Cookies in Server Actions
Mutating cookies — use Server ActionsYou cannot set or delete cookies from a Server Component. Use Server Actions which run on the server when triggered by a Client Component.
'use server'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
export async function login(formData) {
const email = formData.get('email')
const password = formData.get('password')
const token = await authenticateUser(email, password)
// ✅ Set cookie in Server Action
cookies().set('auth-token', token, {
httpOnly: true, // not accessible via JS
secure: true, // HTTPS only
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 7, // 7 days
path: '/',
})
redirect('/dashboard')
}
export async function logout() {
cookies().delete('auth-token')
redirect('/login')
}'use client'
import { login } from '@/app/actions/auth'
export default function LoginForm() {
return (
<form action={login}>
<input name="email" type="email" />
<input name="password" type="password" />
<button type="submit">Login</button>
</form>
)
}Read Cookies in Route Handlers
API routes — app/api/.../route.jsimport { cookies } from 'next/headers'
import { NextResponse } from 'next/server'
export async function GET() {
const cookieStore = cookies()
const token = cookieStore.get('auth-token')?.value
if (!token) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const user = await getUserFromToken(token)
return NextResponse.json(user)
}
export async function POST(request) {
const body = await request.json()
const response = NextResponse.json({ success: true })
// Set cookie in Route Handler response
response.cookies.set('session', body.sessionId, {
httpOnly: true,
secure: true,
maxAge: 3600,
})
return response
}Client-Side Cookie Libraries
When you genuinely need cookies in the browserFor cookies that should be accessible in the browser (non-sensitive preferences), use js-cookie or the native document.cookie API in Client Components.
npm install js-cookie'use client'
import Cookies from 'js-cookie'
import { useState, useEffect } from 'react'
export default function CookieBanner() {
const [accepted, setAccepted] = useState(true)
useEffect(() => {
// Read client-accessible cookie after mount
setAccepted(Cookies.get('cookies-accepted') === 'true')
}, [])
function accept() {
Cookies.set('cookies-accepted', 'true', { expires: 365 })
setAccepted(true)
}
if (accepted) return null
return <div className="fixed bottom-0 ..."><button onClick={accept}>Accept</button></div>
}Never store sensitive data (auth tokens, user IDs) in client-accessible cookies. Use httpOnly cookies via Server Actions or Route Handlers for anything security-sensitive.
Middleware for Cookie-Based Auth
Redirect unauthenticated users at the edgeimport { NextResponse } from 'next/server'
export function middleware(request) {
const token = request.cookies.get('auth-token')?.value
const isAuthPage = request.nextUrl.pathname.startsWith('/login')
const isProtected = request.nextUrl.pathname.startsWith('/dashboard')
// Redirect to login if accessing protected route without token
if (isProtected && !token) {
return NextResponse.redirect(new URL('/login', request.url))
}
// Redirect away from login if already authenticated
if (isAuthPage && token) {
return NextResponse.redirect(new URL('/dashboard', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: ['/dashboard/:path*', '/login'],
}Prevention
- Never import cookies() from 'next/headers' in a file with 'use client'
- Read cookies in Server Components, pass values as props to Client Components
- Use Server Actions to set and delete cookies — not Server Components
- Use middleware for auth-based redirects — runs at the edge before rendering
- For browser-accessible cookies (preferences), use js-cookie in Client Components
Frequently Asked Questions
Why does cookies() only work in Server Components?+−
How do I access cookies in a Client Component?+−
How do I set a cookie in Next.js App Router?+−
How do I read cookies in Next.js middleware?+−
cookies() is not a function — how to fix?+−
How do I delete a cookie in Next.js?+−
Need Expert Help?
We Build Secure Next.js Applications
Softplix builds full-stack Next.js apps with secure authentication. Need help with cookie-based auth or session management? We can help.
Talk to an Engineer