Search code examples
cookiesnext.js

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);


Solution

  • 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