How to use Cookie in React

Managing authentication is one of the most important part of any application. But sometime its become more complex when you start adding more cookies, expiration, jwt etc. In this article we will gonna learn how to use cookie in React applications.

What is js-cookie ?

This package is a simple lightweight vanilla js package for managing the Cookies. This package size is only 944 bytes. It works in all the browser without any dependency requirements. It have 2,095,575 weekly downloads from that we can get idea how popular it is.

Installation

Like any other packages you can simply install it using npm.

npm install js-cookie --save

Usage

Let’s start with some backend code first to get an idea of whole flow. You need to generate your cookie value like token in the backend and then send it to the frontend.

res.status(200).json({ token });

While reading the cookie value in the backend in all the private authorised requests you can access your token like this.

 if (!('token' in req.cookies)) {
      // handle unauhtorized requests
    }
 const { token } = req.cookies;

Let’s move to the frontend part.

First of all you need to import the js-cookie like this.

import cookie from 'js-cookie';

After importing the package you can simply set any cookie using set method in our case its token.

const { token } = await login({ email, password });
      if (token) {
        cookie.set('token', token, { expires: 1 });
        Router.push('/');
      }

You can also set the expire time for your cookie.

Now onward all the request will gonna have the cookie by default.

If you want to remove the cookie on logout. You can simply use the remove method.

cookie.remove('token');

To read a specific cookie you can use get method with cookie name.

Cookies.get('name');

To get all cookie in your website. You can use same get method without cookie name.

Cookies.get(); 

I hope you have learned something new in this article. Please share your valuable comments.

Read full docs.

Visualize your React app using React Sight

Categories: Reactjs

1 Comment

How to add less and svg support to Nextjs - Blog React · October 15, 2020 at 3:21 am

[…] How to use Cookie in React […]

Comments are closed.