Next.js Discord

Discord Forum

Error: Cookies can only be modified in a Server Action... but it is a server action?

Answered
David L. Bowman posted this in #help-forum
Open in Discord
Original message was deleted.
Answered by B33fb0n3
when fetching your own endpoints inside a server component, you need to provide the full url from the api route instead of a relative url like you doing rn

In every case it's not recommended to fetch your own api routes. You want to delete all your cookies now. Why you would want to do that is unclear to me. It is not recommended. For more information read this: https://nextjs-faq.com/fetch-api-in-rsc
View full answer

7 Replies

Original message was deleted
when you calling your server action inside a server component, the server action will be translated to a normal function. And with that it's just a normal function.

You can only modify your cookies inside a server action or route handler. So do that and you will be good to go
Original message was deleted
yea, beeing inside a server component doesn't mean, that you are inside a server action or route handler.

You need to be inside a server action (call a server function from the client for example) or use a route handler
Original message was deleted
you are right, you doing nearly exactly what's written down. There is one difference:

Server components: READ cookies (modifications are NOT allowed)
Server action or route handler: READ, MODIFY cookies (modifications are allowed)

What do you need to do?
Remove the deletion (modify) of your cookies.
Original message was deleted
don't use a server action here as it will be automatically translated to a normal function. Use a route handler instead
Original message was deleted
when fetching your own endpoints inside a server component, you need to provide the full url from the api route instead of a relative url like you doing rn

In every case it's not recommended to fetch your own api routes. You want to delete all your cookies now. Why you would want to do that is unclear to me. It is not recommended. For more information read this: https://nextjs-faq.com/fetch-api-in-rsc
Answer
Original message was deleted
then it's the best to create a page.tsx for that that imports a client component with a button "clear all cookies". On the button click a server action will be called to delete all cookies.

As the server action is called from a client component, the server action works fine. It also doesn't happen on every request then
happy to help