Skip to content

Error: Cookies can only be modified in a Server Action or Route Handler. #51875

@larsniet

Description

@larsniet

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 22.5.0: Mon Apr 24 20:53:44 PDT 2023; root:xnu-8796.121.2~5/RELEASE_ARM64_T8103
    Binaries:
      Node: 18.16.0
      npm: 9.6.7
      Yarn: N/A
      pnpm: 8.6.0
    Relevant Packages:
      next: 13.4.8-canary.5
      eslint-config-next: 13.4.7
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.1.3
    Next.js Config:
      See reproduction repo

Which area(s) of Next.js are affected? (leave empty if unsure)

App directory (appDir: true), Middleware / Edge (API routes, runtime)

Link to the code that reproduces this issue or a replay of the bug

https://github.com/larsniet/server-actions-bug-report

To Reproduce

git clone https://github.com/larsniet/server-actions-bug-report
cd ./server-actions-bug-report
pnpm install && pnpm dev // or npm install && npm run dev

Go to localhost and you should see the error appear in the console.

Describe the Bug

Cookies are not available in server actions.

Using cookies().set() within a server action returns the error:
Cookies can only be modified in a Server Action or Route Handler.

This occurs when trying to implement a server action within any layout (root layout or nested layout). Simply adding the following function within a layout will return the error:

  async function deleteCookie(name: string) {
    "use server";

    try {
      cookies().set({
        name: name,
        value: "",
        expires: new Date("2016-10-05"),
        path: "/",
      });
    } catch (error) {
      console.error(`Error deleting cookie: ${name}`, error);
      throw error;
    }
  }
  await deleteCookie("test");

Expected Behavior

Cookies are handled within a server action, so the error should not occur.

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    RuntimeRelated to Node.js or Edge Runtime with Next.js.bugIssue was opened via the bug report template.locked

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions