Today we are going to learn how we can store and share Cookies between Client Side and Server Side using React.

For today’s tutorial, we will use the library Nookies.
This library will solve our Cookie storage immediately.
First, let’s create a component called CookieStorage.tsx
import nookies from 'nookies' enum CookieKeys { DATO = 'dato', } //Configuración export function getMaxAgeCookie() { return Number.MAX_SAFE_INTEGER; } export function setCookieDato(context: any, valor: string) { setCookies(context, CookieKeys.DATO, valor); } export function getCookieDato(context: any): string { return getCookies(context, CookieKeys.DATO); } //Borrar cookies export function removeCookieDato(context: any) { nookies.destroy(context, CookieKeys.DATO); } export function getCookies(context: any, clave: CookieKeys): string { const cookies = nookies.get(context); return cookies[clave]; } export function setCookies(context: any, clave: CookieKeys, valor: string) { nookies.set(context, clave, valor, { maxAge: getMaxAgeCookie(), // Tiempo de vida de la cookie al máximo path: '/', // La ruta en la que la cookie es válida (en este caso, la raíz del dominio) }); }
In this component, I have created a function to configure Cookies with the maximum lifespan. Also, two functions to read and write Cookies.
With the functions <strong)setCookieData and <strong)getCookieData we can obtain and save new cookies.
Cookies are saved according to the key indicated in the created enum.
To use it, we just have to invoke the functions as follows:
Client Side (from React) pass the context as null:
setCookieDato(null, "Test"); getCookieDato(null);
Server Side (from Next.js in getServerSideProps or getStaticProps) pass the context from the Next function:
export async function getServerSideProps(context: any) { ... setCookieDato(context, "Test"); getCookieDato(context); ... }
