Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Almacenar Cookies y compartir en Server Side desde Client Side en Next.js

Tiempo de lectura: 2 minutos

Hoy vamos a aprender cómo podemos almacenar Cookies y compartirlas entre Client Side y Server Side usando React.

Para el tutorial de hoy vamos a utilizar la librería Nookies.

Esta librería nos solucionará el almacenamiento de Cookies de forma inmediata.

Primero vamos a crear un componente llamado CookieStorage.tsx

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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)
});
}
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) }); }
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)
    });
}

En este componente he creado una función para configurar las Cookies con el máximo tiempo de ciclo de vida. Además dos funciones para leer y escribir las Cookies.

Con las funciones setCookieDato y getCookieDato podremos obtener y guardar nuevas cookies.

Las cookies se guardan según la clave que se indica en el enum creado.

Para utilizarlo simplemente tendremos que invocar las funciones de la siguiente forma:

Client Side (desde React) el context se pasa a null:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
setCookieDato(null, "Test");
getCookieDato(null);
setCookieDato(null, "Test"); getCookieDato(null);
setCookieDato(null, "Test");
getCookieDato(null);

Server Side (desde Next.js en getServerSideProps o getStaticProps) el context se pasa desde la función de Next:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export async function getServerSideProps(context: any) {
...
setCookieDato(context, "Test");
getCookieDato(context);
...
}
export async function getServerSideProps(context: any) { ... setCookieDato(context, "Test"); getCookieDato(context); ... }
export async function getServerSideProps(context: any) {
  ...

  setCookieDato(context, "Test");
  getCookieDato(context);
  ...
}
0

Deja un comentario