[reactjs] How can I set a cookie in react?

Orginally, I use the following ajax to set cookie.

function setCookieAjax(){
  $.ajax({
    url: `${Web_Servlet}/setCookie`,
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    headers: { 'Access-Control-Allow-Origin': '*',
               'username': getCookie("username"),
              'session': getCookie("session")
    },
    type: 'GET',
    success: function(response){
      setCookie("username", response.name, 30);
      setCookie("session", response.session, 30);}
  })
}

function setCookie(cname, cvalue, minutes) {
    var d = new Date();
    d.setTime(d.getTime() + (minutes*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

export const getUserName = (component) => {
    setCookieAjax()
 $.ajax({
    url: `${Web_Servlet}/displayHeaderUserName`,
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    headers: { 'Access-Control-Allow-Origin': '*',
                'username': getCookie("username"),
                'session': getCookie("session")
            },
    type: 'GET',
    success: function(response){
        component.setState({
        usernameDisplay: response.message
        })
   }.bind(component)
 })
}

Now, I want to set the cookie using the servlet's adding cookie function. But I don't know how to achieve my purpose.

Cookie loginCookie = new Cookie("user",user);  //setting cookie to expiry in 30 mins
        loginCookie.setMaxAge(30*60);
        loginCookie.setDomain("localhost:4480");
        loginCookie.setPath("/");

response.addCookie(loginCookie);

In order to extend the cookie timelimit, what should I write in the react side to receive the cookie's session time?

This question is related to reactjs cookies

The answer is


Little update. There is a hook available for react-cookie

1) First of all, install the dependency (just for a note)

yarn add react-cookie

or

npm install react-cookie

2) My usage example:

// SignInComponent.js
import { useCookies } from 'react-cookie'

const SignInComponent = () => {

// ...

const [cookies, setCookie] = useCookies(['access_token', 'refresh_token'])

async function onSubmit(values) {
    const response = await getOauthResponse(values);

    let expires = new Date()
    expires.setTime(expires.getTime() + (response.data.expires_in * 1000))
    setCookie('access_token', response.data.access_token, { path: '/',  expires})
    setCookie('refresh_token', response.data.refresh_token, {path: '/', expires})

    // ...
}

// next goes my sign-in form

}

Hope it is helpful.

Suggestions to improve the example above are very appreciated!


A very simple solution is using the sfcookies package. You just have to install it using npm for example: npm install sfcookies --save

Then you import on the file:

import { bake_cookie, read_cookie, delete_cookie } from 'sfcookies';

create a cookie key:

const cookie_key = 'namedOFCookie';

on your submit function, you create the cookie by saving data on it just like this:

bake_cookie(cookie_key, 'test');

to delete it just do

delete_cookie(cookie_key);

and to read it:

read_cookie(cookie_key)

Simple and easy to use.


By default, when you fetch your URL, React native sets the cookie.

To see cookies and make sure that you can use the https://www.npmjs.com/package/react-native-cookie package. I used to be very satisfied with it.

Of course, Fetch does this when it does

credentials: "include",// or "some-origin"

Well, but how to use it

--- after installation this package ----

to get cookies:

import Cookie from 'react-native-cookie';

Cookie.get('url').then((cookie) => {
   console.log(cookie);
});

to set cookies:

Cookie.set('url', 'name of cookies', 'value  of cookies');

only this

But if you want a few, you can do it

1- as nested:

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1')
        .then(() => {
            Cookie.set('url', 'name of cookies 2', 'value  of cookies 2')
            .then(() => {
                ...
            })
        })

2- as back together

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1');
Cookie.set('url', 'name of cookies 2', 'value  of cookies 2');
Cookie.set('url', 'name of cookies 3', 'value  of cookies 3');
....

Now, if you want to make sure the cookies are set up, you can get it again to make sure.

Cookie.get('url').then((cookie) => {
  console.log(cookie);
});

I set cookies in React using the react-cookie library, it has options you can pass in options to set expiration time.

Check it out here

An example of its use for your case:

import cookie from "react-cookie";

setCookie() => {
  let d = new Date();
  d.setTime(d.getTime() + (minutes*60*1000));

  cookie.set("onboarded", true, {path: "/", expires: d});
};

You can use default javascript cookies set method. this working perfect.

createCookieInHour: (cookieName, cookieValue, hourToExpire) => {
    let date = new Date();
    date.setTime(date.getTime()+(hourToExpire*60*60*1000));
    document.cookie = cookieName + " = " + cookieValue + "; expires = " +date.toGMTString();
},

call java scripts funtion in react method as below,

createCookieInHour('cookieName', 'cookieValue', 5);

and you can use below way to view cookies.

let cookie = document.cookie.split(';');
console.log('cookie : ', cookie);

please refer below document for more information - URL


Use vanilla js, example

document.cookie = `referral_key=hello;max-age=604800;domain=example.com`

Read more at: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie