Next.js Discord

Discord Forum

Directly calling Server Actions from Server Components

Unanswered
Barbary Lion posted this in #help-forum
Open in Discord
Avatar
Barbary LionOP
I need to set a cookie in a Server Component route. This is not directly possible, but it can be done from Server Actions and Routes. I can't figure out how to invoke a Server Action from a Server Component. Server Actions can be invoked as Form Actions or as though they were regular async functions from Client Components, but attempting to call it as an async function from a Server Component is resulting in:

Unhandled Runtime Error 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

Presumably this is because NextJS is not converting the function call to a POST request under the hood. Is there a way to invoke the action in a simple way, or do I need to just go ahead and explicitly create a route and use fetch to invoke it?

page.tsx:

import { cookies } from "next/headers"; export default async function ServerActionFromServerComponent() { async function serverAction() { "use server"; cookies().set("serverAction", "cookieValue"); } await serverAction(); return <div>Hello</div>; }

3 Replies

Avatar
jason
Have you tried using the middleware to set the cookie for this specific page?
Avatar
joulev
if you call a server action in a server component, you are merely invoking it as a regular server-side function, and it won't work as a server action.

you cannot set cookies in server components, that's a fundamental limitation and there are no workarounds.

use middleware instead.
Avatar
Barbary LionOP
That makes sense and I may try that later. I ended up getting my use case working by creating a route handler that stores the cookie and then redirects to the page. Switching to middleware will remove a redirect.