Next.js Discord

Discord Forum

cookies().set() in server component

Answered
PepeW posted this in #help-forum
Open in Discord
Avatar
I have a file @/actions/cart.server.actions and inside of it I have a function handleGetCart() that does a cookies().set("cartToken", cart.tokenValue).

Here's the file:
"use server"

import { cookies } from "next/headers"

export async function handleGetCart(): Promise<CartResponse | undefined> {
  {/* some code ... */}
  cookies().set("cartToken", cart.tokenValue)
  {/* some code ... */}
}


Now I'm calling this function in different server components like page.tsx or layout.tsx.

For example:
import { handleGetCart } from "@/actions/cart.server.actions"

export default async function CartLayout({ children }: { children: ReactNode }) {
  const cart = await handleGetCart()

  return (
    ...
  )
}

But I get the following error: Error: Cookies can only be modified in a Server Action or Route Handler.
I've read the docs but I don't get why i's not working (I've added the experimental property)
Answered by Julienng
Hi, server action a meant to be used as "POST" functions, but you are calling it during a get (your current page).

To make it work, you need to pass your server action to the action props on a form element.

You can see an example here :
https://nextjs.org/docs/app/api-reference/functions/server-actions#import
View full answer

6 Replies

Avatar
Hi, server action a meant to be used as "POST" functions, but you are calling it during a get (your current page).

To make it work, you need to pass your server action to the action props on a form element.

You can see an example here :
https://nextjs.org/docs/app/api-reference/functions/server-actions#import
Answer
Avatar
If you need to set a cookie during a get of a page, you can take a look at middleware to set your cookie.
Avatar
Hi, Ok I get it.
And using route handlers could work for me (as stated is the docs) or should I just use the middleware ?
Avatar
Route handler vs middleware is :
- if you need to set up your cookie before the route is called : middleware
- otherwise, a route handler can be enough (like calling a route-handler on the browser after render)
Avatar
Oh ok ! So i'll stick to the middleware then.
Thank you for your time 🙂
Avatar
With pleasure, have fun coding