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

10 messages · Page 1 of 1 (latest)

tough flame
#

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
  }
}
undone tapirBOT
#

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

tiny ibex
#

you just invoke the function on the server component

tough flame
#

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

tiny ibex
tough flame
#

thats a shame, ah well, i'll need to have a look at that then