Your AI coding agent set a cookie in a page, and Next.js says cookies can only be modified in a Server Action or Route Handler

AI coding agents call cookies().set() while a page renders, which Next.js does not allow. Here is why reading works but writing does not, and how to move the write into a Server Function or Route Handler.

מעבר לתיקון
בעמוד הזה

You asked your AI coding agent to remember a visitor’s theme, or to log someone out. It wrote cookieStore.set('theme', 'dark') inside a page, the code reads perfectly, and Next.js stops with “Cookies can only be modified in a Server Action or Route Handler.” Sometimes it only breaks after you deploy.

The cause is where the agent put the call, not how it wrote it. The fix is to move the write into the right kind of function.

Why this happens

Reading and writing cookies are different jobs. The Next.js docs for cookies say it is an async function that lets you read incoming request cookies in Server Components, and read and write outgoing cookies only in Server Functions or Route Handlers.

The docs give the reason: cookies are a client-side storage mechanism. The server can only send a Set-Cookie header telling the browser to store one. A Server Component is rendered while the response is already streaming, and the docs state that HTTP does not allow setting cookies after streaming starts. So .set and .delete are not supported during Server Component rendering.

Agents mix this up because reading and writing look identical in the code. (await cookies()).get('theme') is fine in a page. The same object’s .set('theme', 'dark') in that page is not.

How to tell if this is your problem

  1. Read the stack trace. Find the file that calls .set( or .delete( on the cookie store.
  2. Check what kind of function it sits in. If it is a page, a layout, or a plain helper called while rendering, that is the problem. If it is a function marked 'use server' or a route.js handler, the cause is something else.
  3. Check for 'use server' helpers called straight from a page body. Calling a Server Function during render, instead of from a form or a click handler, runs it as ordinary render code.

The fix

Move the write into a Server Function, and trigger it from the client. This is the pattern from the Next.js docs:

// 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: '/' })
}

Then pass it to a form, so it runs when the user submits instead of while the page renders:

import { setTheme } from './actions'

export default function Page() {
  return (
    <form action={setTheme.bind(null, 'dark')}>
      <button type="submit">Dark mode</button>
    </form>
  )
}

The page itself keeps only the read, which is allowed in a Server Component:

import { cookies } from 'next/headers'

export default async function Page() {
  const cookieStore = await cookies()
  const theme = cookieStore.get('theme')
  return <p>Current theme: {theme?.value ?? 'light'}</p>
}

If the write has to happen on a request that is not a form, such as a sign-in callback, put it in a Route Handler (app/api/.../route.js). The docs list that as the other place where .set and .delete work.

.delete can only be called in a Server Function or Route Handler, and only for a cookie on the same domain that set it. The docs list two other ways to clear one: set the same name with an empty value, or set maxAge: 0, which expires it immediately. All three belong in a Server Function or Route Handler too.

Refresh cached data after the write

After a cookie changes in a Server Function used as a Server Action, Next.js can return the updated UI and new data in one round trip. To refresh cached data as well, the docs say to call revalidatePath or revalidateTag inside the same function.

Why it sometimes only fails in production

Several forum reports describe this error appearing after deploy and not in local development. We could not confirm one cause for that, so treat it as a sign to review every write, not just the one in the stack trace: search for .set( and .delete( on cookie stores and check each one sits inside a 'use server' function or a route handler.

How to avoid this next time

Tell the agent the rule up front: “In Next.js App Router, read cookies in Server Components. Set or delete them only in Server Functions or Route Handlers, never during render.” In review, search the diff for .set( and .delete( and check which function each one lives in.

Comments