Directly calling Server Actions from Server Components
Unanswered
Barbary Lion posted this in #help-forum
![Avatar](https://cdn.discordapp.com/embed/avatars/5.png)
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:
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:
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](https://cdn.discordapp.com/avatars/129797070721777664/0a6f95634929c73bc534a166a090b4a1.webp?size=256)
jason
Have you tried using the
middleware
to set the cookie for this specific page?![Avatar](https://cdn.discordapp.com/avatars/484037068239142956/44415017de6fed2ccd5d44b4b2051ac0.webp?size=256)
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.
you cannot set cookies in server components, that's a fundamental limitation and there are no workarounds.
use middleware instead.
![Avatar](https://cdn.discordapp.com/embed/avatars/5.png)
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.