Next.jsApp RouterError Fix2026 Updated

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

January 20266 min readNext.js 13–15 · App Router

⚡ Quick Fix — Read in Server, Pass as Prop

app/dashboard/page.jsx
// ✅ 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
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.

WhereRead cookiesSet cookies
Server Componentcookies().get(name)❌ Not allowed
Server Actioncookies().get(name)cookies().set(name, value)
Route Handler (GET/POST)cookies().get(name)cookies().set(name, value)
Middlewarerequest.cookies.get(name)response.cookies.set(name, value)
Client Component❌ Cannot use cookies()document.cookie (not recommended)
1

Read Cookies in a Server Component

Correct pattern — Server Component only
1 min
app/profile/page.jsx
import { 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>
}
2

Pass Cookie Values as Props to Client Components

The correct way to use cookie data in Client Components
2 min

Client Components cannot call cookies() but they can receive cookie values as props from a parent Server Component.

app/settings/page.jsx — 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>
  )
}
components/ThemeToggle.jsx — Client Component
'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>
}
3

Set and Delete Cookies in Server Actions

Mutating cookies — use Server Actions
3 min

You cannot set or delete cookies from a Server Component. Use Server Actions which run on the server when triggered by a Client Component.

app/actions/auth.js
'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')
}
components/LoginForm.jsx
'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>
  )
}
4

Read Cookies in Route Handlers

API routes — app/api/.../route.js
2 min
app/api/user/route.js
import { 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
}
5

Client-Side Cookie Libraries

When you genuinely need cookies in the browser
2 min

For cookies that should be accessible in the browser (non-sensitive preferences), use js-cookie or the native document.cookie API in Client Components.

terminal
npm install js-cookie
components/CookieBanner.jsx
'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.

6

Middleware for Cookie-Based Auth

Redirect unauthenticated users at the edge
3 min
middleware.js
import { 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

Frequently Asked Questions

Why does cookies() only work in Server Components?+
cookies() from 'next/headers' reads HTTP request headers which are only available on the server. Client Components run in the browser where there is no HTTP request object. This is an intentional security boundary — cookie parsing happens server-side.
How do I access cookies in a Client Component?+
Read the cookie in a Server Component using cookies(), then pass the value as a prop to the Client Component: const token = cookies().get('token')?.value; return <ClientComp token={token} />. Never import cookies() in a Client Component.
How do I set a cookie in Next.js App Router?+
Use Server Actions or Route Handlers: import { cookies } from 'next/headers'; cookies().set('name', 'value', { httpOnly: true, secure: true, path: '/' }). You cannot set cookies directly from Server Components — only from Server Actions or Route Handlers.
How do I read cookies in Next.js middleware?+
Middleware has its own cookie API: export function middleware(request) { const token = request.cookies.get('token')?.value; const response = NextResponse.next(); response.cookies.set('visited', 'true'); return response; }
cookies() is not a function — how to fix?+
Make sure you import from 'next/headers': import { cookies } from 'next/headers'. Do not import from 'next/cookies' or any other path. Also ensure the component is a Server Component (no 'use client' directive).
How do I delete a cookie in Next.js?+
In a Server Action or Route Handler: cookies().delete('tokenName'). Or set it with maxAge 0: cookies().set('token', '', { maxAge: 0 }). You cannot delete cookies from a Server Component — only from actions and handlers.

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