Next.js Discord

Discord Forum

Calling server action from Layout - Not possible?

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
Hi - I am trying to set a cookie from the layout - I know we can't do it directly in the layout file, and it has to be done through server actions.
However, when I call a server action that would set the cookie, I get the following error:

unhandledRejection: th [Error]: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options
  at Proxy.callable (/Users/ssardorf/dev/12s12m/verk/node_modules/.pnpm/next@14.1.0_@babel+core@7.26.0_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:36:12692)
   at setSelectedGuildIdCookie (webpack-internal:///(rsc)/./app/communities-dashboard/(dashboard)/actions.ts:25:61)
   at Layout (webpack-internal:///(rsc)/./app/communities-dashboard/(dashboard)/layout.tsx:75:110)


Is it straight up not possible to set a cookie from a layout file, even when using server actions?

2 Replies

Asian black bear
You can't set cookies during rendering. The hint that cookies can be modified as part of server actions means that it can only be done as part of a separate API request from the client without rendering pages or layouts.
Indian oil sardine
I prefer to use a middleware for everything cookies-related. Maybe you could do that?