hlasensky
hlasensky

Reputation: 43

Can't set cookie in server action Next js 13.4

Im trying to set a cookie in actions and it giving me an error: Cookies can only be modified in a Server Action or Route Handler, but I have them in the server action.

path is app/actions.ts

import { cookies } from "next/headers";


export async function getCookie() {
    "use server";
    const cookieStore = cookies();

    const calenderId = cookieStore.get("calenderId")?.value;

    return Promise.resolve(calenderId);
}

export async function setCookie(id: string) {
    "use server";
    
    cookies().set("calenderId", id);
}

I tried to do it in the server component, but that didn't work either.

Here is a part where I call setCookies() it's in app/page.tsx and it's server component

if (!calenderId) {
    calender = await prisma.calendar.create({ data: {} });
    await setCookie(calender.id);

Upvotes: 4

Views: 3912

Answers (2)

Marcel Fahle
Marcel Fahle

Reputation: 153

You cannot call server actions like ordinary functions, at least not in server components. From the docs:

You can invoke Server Actions using the following methods:

Using action: React's action prop allows invoking a Server Action on a element.

Using formAction: React's formAction prop allows handling , , and elements in a .

Custom Invocation with startTransition: Invoke Server Actions without using action or formAction by using startTransition. This method disables Progressive Enhancement.

Upvotes: 2

AnasSafi
AnasSafi

Reputation: 6274

The only workaround that worked for me was to call the server function inside useEffect as shown below:

useEffect(() => {
    setCookie("newId").then();
}, []);

This is bug in nextjs, you can follow this bug here: https://github.com/vercel/next.js/issues/51875

Upvotes: 3

Related Questions