Storing Cookies and Sharing from Client Side to Server Side in Next.js

Tiempo de lectura: 2 minutos

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 {
    DATA = 'data',
}

// Configuration
export function getMaxAgeCookie() {
    return Number.MAX_SAFE_INTEGER;
}

export function setCookieData(context: any, value: string) {
    setCookies(context, CookieKeys.DATA, value);
}

export function getCookieData(context: any): string {
    return getCookies(context, CookieKeys.DATA);
}

// Delete cookies
export function removeCookieData(context: any) {
    nookies.destroy(context, CookieKeys.DATA);
}

export function getCookies(context: any, key: CookieKeys): string {
    const cookies = nookies.get(context);
    return cookies[key];
}

export function setCookies(context: any, key: CookieKeys, value: string) {
    nookies.set(context, key, value, {
        maxAge: getMaxAgeCookie(), // Maximum cookie lifespan
        path: '/', // The path where the cookie is valid (in this case, the root of the domain)
    });
}

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 setCookieData and 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:

setCookieData(null, "Test");
getCookieData(null);

Server Side (from Next.js in getServerSideProps or getStaticProps) pass the context from the Next function:

export async function getServerSideProps(context: any) {
  ...

  setCookieData(context, "Test");
  getCookieData(context);
  ...
}

Leave a Comment