Setting cookies with Server Actions in Next.js 13.4 – Cookies

by
Alexei Petrov
cookies next.js

Quick Fix: Consider awaiting the setting of the cookie in the create function.Additionally, you can try debugging the issue by using a useState and useEffect combination in the LocaleSwitcher component to see if there’s a constant re-rendering.

The Problem:

a user wants to implement a locale switcher component in Next.js 13.4. He is using a server action to set a cookie to store the user’s preferred language. However, when he tries to call the server action from a form submit event, the server action fails to set the cookie.
The developer has checked the Next.js documentation and also tried different approaches. He is getting different errors like "Warning: Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported." and "Cookies can only be modified in a Server Action or Route Handler".
The user is confused and doesn’t know what he is doing wrong and how to fix the errors.

Q&A

Using server action within a useEffect in Next.js 13.4

Server actions should not be used within a useEffect as it can cause rerenders and infinite logging.

Server action argument and return value type in Next.js 13.4

Server actions must take in serialized arguments and return a serialized value.

Video Explanation:

The following video, titled "Client and Server Side Cookies in Next.js - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Let's learn how to set/remove cookies both in the browser but also on the server in Next.js. This will allow us to create HttpOnly cookies, ...