Open lukebelbina opened 1 month ago
Hi, first of all there is a logical problem with your code, against whom do you want to set the cookie? (who is the client ). Since the location you are executing the code is your '/' route (app/page.tsx) file, the code will be statically generated on compile thus your self-invoking function setCookieServerAction will also be executed(from the server), you can see an error message in your server console telling that you can only modify (set) the cookies from server actions or route handlers, what this means is that putting "use server" in a route page does not make it a server action, extract your server action function and make a new file for your server actions only, usually at lib/actions.js (with "use server"),This file only exports the server actions and has no rendering logic unlike the route pages. Another thing is that you should call the server action from a client component, either using controlled method like button onClick or useEffect on mount.
Link to the code that reproduces this issue
https://github.com/lukebelbina/nextjs-cookie-server-action-bug
To Reproduce
Create the following Page in Next Js 14.2.5.
Navigate to the page and you should see the error:
I have tried a bunch of different ways to do this based on the documentation but all of the result in the same error. My understanding is this is a server action. I also tried a route.
Current vs. Expected behavior
Expect the cookie to be set
Provide environment information
Which area(s) are affected? (Select all that apply)
Not sure
Which stage(s) are affected? (Select all that apply)
next dev (local), next start (local)
Additional context
No response