Working with browser cookie in React

Working with browser cookie in React

Written by krissanawat101 on Feb 4th, 2021 Views Report Post

Cookies are an essential piece of component that is highly used when browsing any website in a web browser. They are small text files that store certain information about the users' device, authentication information, sessions, and other tracking information so that the user experience and interaction with the website becomes smooth and optimized. They are stored in browsers mainly in the form of name-value peers. They can be used to store the personalization data so that each time you visit the website, you get your own personalized website view and features. They can also store the authentication information so that each time you visit the website, you won't have to re-login again and again. They can be used to track the user activities on the website so that the next time, each activity becomes intuitive. Overall, they optimize the internet as well as website experience for the end-users.

In this tutorial, we are going to learn the mechanism of setting and fetching the cookie to and from the webpage in React web application. This process can be easily done by using the react-cookie package. The overall process is simple and easy. We can make use of the cookie provider component along with hooks to set and fetch the cookie. The idea is to learn how to set and get cookies in the functional components of the React ecosystem.

So, let's get started!

Installing the Required package

First, we need to install the react-cookie package in our project. For that, we need to execute the following command in our root project terminal:

yarn add react-cookie

Now in order to configure the cookie provider throughout the React app, we need to import the CookiesProvider component from the react-cookie package. Then, we need to wrap our root i.e. App component with it.

This is to be done in the index.js file as shown in the code snippet below:

import React from "react";
import ReactDOM from "react-dom";
import { CookiesProvider } from "react-cookie";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
       <CookiesProvider>   
         <App />  
      </CookiesProvider>,  
      rootElement
);

Now, in order to set a cookie, we need to import the useCookies() hook from the react-cookie package.

The useCookies() hook takes the array with cookie-name as its input and returns the cookies object, and setCookie() method. The cookies object holds all of the cookies that we have created in our app. The setCookie() method can be used to set a cookie to our React application.

The overall process of setting the cookie in a React functional component by using the useCookies hook is shown in the code snippet below:

import React from "react";
import { useCookies } from "react-cookie";
export default function App() {
  const [cookies, setCookie] = useCookies(["member"]);
  function createCookie() {
    setCookie("member", "krissanawat", {
          path: "/" });
     }
  return (
    <div className="App">
      <h3>Example code on React cookies</h3>
      <button onClick={createCookie}>Create Cookie</button>  
   </div>
  );
}

In the above code, we have passed three properties to the setCookie() method, the first one is the name of the cookie, the second is the cookie value and the third is the options object where we have used path: "/" to access the cookie in all pages.

To understand more options such as cookie duration, httpOnly, secured, etc. we can check out the official package documentation.

Now in App.js, we can access as well as set cookie as shown in the code snippet below:

import React from "react";
import { useCookies } from "react-cookie";
export default function App() {
  const [cookies, setCookie] = useCookies(["member"]);

  function CreateCookie() {
    setCookie("member", "krissanawat", {
      path: "/"
    });
  }
  return (
    <div className="App">
      <h1>How to set React cookies</h1>
      
    <button clas="btn btn-primary" onClick={CreateCookie}>Create Cookie</button>
		 <p>Show cookie : </p>{cookies.member && <p>{cookies.member}</p>}  
    </div>
  );
}

Here, we are going to explore how to fetch cookie information from the browser in a React application using the react-cookie package.

First, we need to import the CookiesProvider component from the react-cookie package and wrap our root app component just as before as shown in the code snippet below:

import React from "react";
import ReactDOM from "react-dom";
import { CookiesProvider } from "react-cookie";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <CookiesProvider>    
		<App />  
	</CookiesProvider>,  
	rootElement
);

Now, inside our React component, we can access the cookie by using a useCookies() hook as shown in the code snippet below:

import React from "react";
import { useCookies } from "react-cookie";
export default function App() {
  const [cookies, setCookie] = useCookies();
	return (
    <div className="App">
      <h3>How to get React cookies</h3>
      {cookies.user && <p>{cookies.user}</p>}    
		</div>
  );
}

The cookies object that we have created in our app holds all the cookies.

In the case of class components, we can set as well as fetch the cookie by using a withCookies() higher-order component. We wrap our main component with withCookies HOC, the cookies object will be available as a prop in the component. By accessing the cookies component from props, we can set as well as fetch the required cookie in the class components.

Finally, we have successfully learned how to set and fetch the cookies in our React web application.

However, in some scenarios a cookie cannot be fetched in a React web app:

  • We cannot access cookie from all the pages if we do not set a cookie path as /.
  • If we set the httpOnly option in the cookie to the response, then we cannot access it inside the react app. This is because the browser directly embeds the cookie to an HTTP header.

Conclusion

The main objective of this article was to explore the setting and fetching of cookie information on a React web application. Due to the availability of the react-cookie package, the overall configuration was simple and easy. We basically had to use a cookie provider component along with either hook or higher-order function to set and get access to cookie information in a React app. Such cookie can be set to store the user based information as well as access it in the web app provide a better website experience for the internet users.

Comments (0)