Next.js Discord

Discord Forum

"Cookies can only be modified in a Server Action or Route Handler."

Answered
Ragdoll posted this in #help-forum
Open in Discord
RagdollOP
Hello, I'm having some troubles handling cookies.

Currently, I have a component which fetches the basket from an server action, which then returns the basket, or if it doesn't exist it creates one and assigns a cookie for it.

I keep getting an error when trying to assign the cookie though, would love it if anyone could share their thoughts concerning this.

Example:

(component)
"use server";

import { getBasket } from 'app/actions';

export default async function Page() {
  const basket = await getBasket();

  return <>{JSON.stringify(basket)}</>;
}


(actions)
"use server";

export async function getBasket() {
  const basketId = cookies().get('basketId')?.value;

  if (basketId) {
    // fetches & returns basket here, doesnt concern this issue
  } else {
    // (act like basket is fetched here)

    cookies().set("basketId", basket.ident) // THIS errors
  }
}
Answered by Ray
unfortunately, yes, need to make a client component to invoke the server action
View full answer

8 Replies

RagdollOP
Ah, so the invoking component would need to be a client component?
Or is there some other way to solve this? As it would be a bit tedious to refactor it into a client component
@Ragdoll Ah, so the invoking component would need to be a client component?
unfortunately, yes, need to make a client component to invoke the server action
Answer
RagdollOP
thats a shame, ah well, i'll need to have a look at that then