#Directly calling Server Actions from Server Components

4 messages · Page 1 of 1 (latest)

karmic jackal
#

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>;
}`

grand eagleBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

small night
#

Have you tried using the middleware to set the cookie for this specific page?

bronze sonnet