How to set samesite cookie attribute in react js

To set the SameSite attribute for a cookie in ReactJS, you can use the following approach:

1. Install the js-cookie library by running the command:

    npm install js-cookie
  

2. Import the library in your React component where you want to set the cookie:

    import Cookies from 'js-cookie';
  

3. Set the SameSite attribute by calling the Cookies.set() method with the sameSite option:

    
      Cookies.set('cookieName', 'cookieValue', {'{'} sameSite: 'none' {'}'});
    
  

In the above code, the ‘cookieName’ and ‘cookieValue’ represent the name and value of your cookie. The sameSite: ‘none’ option sets the SameSite attribute as None, which allows the cookie to be sent on both cross-site and same-site requests.

4. To retrieve the cookie value, you can use the Cookies.get() method:

    
      const cookieValue = Cookies.get('cookieName');
      console.log(cookieValue);
    
  

The cookieValue variable will contain the value of the cookie.

Note: Ensure that you set the SameSite attribute as ‘None’ and use secure cookies (by setting the ‘Secure’ attribute) to comply with the latest browser security requirements for cross-site cookies.

Leave a comment