Setting or deleting a cookie in Next.js throws instead of saving it
Error: Cookies can only be modified in a Server Action or Route HandlerShort answer
Next.js only lets you write cookies where the response headers can still be changed: a Server Function (Server Action) or a Route Handler. Reading cookies in a Server Component is fine, but set and delete during rendering fail. Move the write into an action or a route, await cookies(), and delete on the same domain that set the cookie.
Fix it fast
1Find out which cause you have
Find every place that writes a cookie, then check whether each one runs inside a file with 'use server' or inside a route.ts handler.
grep -rn "cookies()\|cookieStore\.\(set\|delete\)" app lib components2Match what you see, then jump to its fix
- 1
The stack trace goes through page.tsx, layout.tsx or a helper they call, not through an action or route.tsThe write runs while a Server Component rendersFix - 2
The code calls cookies().set(...) or cookies().get(...) directly, with no awaitcookies() is not awaited (code written for Next.js 14)Fix - 3
No error, but the cookie is still sent on the next requestdelete() does not match how the cookie was setFix
- 1
What does the error look like?
Error: Cookies can only be modified in a Server Action or Route Handlercookies().set() works in a form action but throws when called from a page or layoutcookies().delete() runs without an error but the cookie stays in the browser
Cause 1 of 3
The write runs while a Server Component renders
1Check
Rendering is a read-only phase for cookies. A helper that calls cookieStore.set is fine only when its caller is a Server Function or a Route Handler. If a page calls it directly, or a page calls a helper that calls it, the write happens during render.
grep -rln "'use server'\|\"use server\"" app lib; ls app/api 2>/dev/null2Fix
Put the write in a Server Function and trigger it from the client (a form action or an event handler), or in a Route Handler that the client calls.
// app/actions.ts
'use server'
import { cookies } from 'next/headers'
export async function setTheme(theme: string) {
const cookieStore = await cookies()
cookieStore.set('theme', theme, { httpOnly: true, path: '/' })
}3Verify
Call the action from a form or button, then look at the Set-Cookie header in the response.
curl -i -X POST http://localhost:3000/api/theme # example Route Handler pathConfirmed by nextjs.org
Cause 2 of 3
cookies() is not awaited (code written for Next.js 14)
1Check
In Next.js 15 and later cookies() is an async function that returns a promise. Synchronous access still works in 15 but is deprecated, so an old snippet may behave oddly or fail on a newer version.
grep -rn "cookies()\." app lib components2Fix
Await the call first, keep the result in a variable, and call set or delete on that variable. The Next.js 15 upgrade guide lists a codemod for this change.
const cookieStore = await cookies()
cookieStore.set('session', token, { httpOnly: true, secure: true })3Verify
Run the type check and the action again.
npx tsc --noEmitConfirmed by nextjs.org
Cause 3 of 3
delete() does not match how the cookie was set
1Check
delete only works for a cookie that belongs to the domain the code runs on, and the code must run on the same protocol (HTTP or HTTPS) as the cookie. For wildcard domains, the subdomain must match exactly. A cookie set with another path or domain option is a different cookie.
curl -s -i http://localhost:3000/ | grep -i set-cookie2Fix
Delete it with the same domain and path you set it with, or expire it by setting the same name with maxAge: 0.
const cookieStore = await cookies()
cookieStore.set('session', '', { path: '/', maxAge: 0 })3Verify
Repeat the request and check that the browser no longer lists the cookie under Application > Cookies.
curl -i -X POST http://localhost:3000/api/logoutConfirmed by nextjs.org
How do I stop it coming back?
- Treat Server Components as read-only for cookies; keep every write in a file marked 'use server' or in route.ts.
- Name cookie helpers so the caller sees whether they read (getTheme) or write (setTheme).
- Use one place to define cookie options (path, domain, secure, httpOnly) so set and delete always match.
- Read the upgrade guide for each major Next.js version before bumping it.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Web apps
Apollo Server rejects a request as a potential CSRF
HTTP 400 Bad Request from the GraphQL endpoint
Apollo Server's CSRF prevention is on by default.
3 causes, each with a fixWeb apps
Clerk cannot read its publishable key in a Next.js app
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY is undefined
Clerk reads NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY.
3 causes, each with a fixWeb apps
The shell cannot find create-next-app
command not found: create-next-app
create-next-app is not meant to be installed as a shell command.
2 causes, each with a fixWeb apps
ESLint fails with: Cannot find module 'next/babel'
ESLint stops on the first file with a Babel or parser error instead of listing lint results
next/babel is a Babel preset that ships inside the next package.
3 causes, each with a fixWeb apps
Firebase Auth says the API key is not valid
Firebase: Error (auth/api-key-not-valid.-please-pass-a-valid-api-key.)
The apiKey your app sends is either empty, wrong, or blocked.
4 causes, each with a fixWeb apps
Jest fails with SyntaxError: Unexpected token when testing a Next.js component
Jest failed to parse a file.
Jest only understands plain JavaScript until a transform and a few file mappings tell it more.
3 causes, each with a fix