Orginally, I use the following ajax to set cookie.

function setCookieAjax(){
    url: `${Web_Servlet}/setCookie`,
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
               '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) => {
    url: `${Web_Servlet}/displayHeaderUserName`,
                'username': getCookie("username"),
                'session': getCookie("session")
    type: 'GET',
    success: function(response){
        usernameDisplay: response.message

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


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


It appears that the functionality previously present in the react-cookie npm package has been moved to universal-cookie. The relevant example from the universal-cookie repository now is:

import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman
  • hi, I have installed this package but getting some error when Import it Error: ENOENT: no such file or directory, open 'D:\XXX project\user 22 oct\Application1\node_modules\universal-cookie\node_modules\cookie\index.js'
    – K.S
    Oct 30 '19 at 7:54
  • @K.S npm install universal-cookie? Check the path in the message. If its not there, you have not installed it.
    – C4d
    May 25 '20 at 9:26
  • this package has some problems. You have access to cookies as long as you haven't reload the page. After reloading, you'll get undefined (May be beacause of the line var cookies = new Cookies(), I don't know). so tiring. I have spent a day on this problem but no answer yet. I'm going to change my cookies package. Oct 27 '20 at 6:19

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


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();

  cookie.set("onboarded", true, {path: "/", expires: d});
  • 3
    It appears that the react-cookie package has updated (broken) the API used in this solution. +1 for the link, and I've posted the updated answer below. Apr 28 '17 at 15:37

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


and to read it:


Simple and easy to use.

  • 2
    I have tried react-cookie, universal-cookie and after a day of struggling with undefined result of cookies.get("cookie_name") of these packages, I finally came across this solution and the package sfcookies worked for me. Thank you so much! You saved me! Oct 27 '20 at 7:27

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


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!

  • what does the response variable do and what value is it getting? also where is the ideal place to set the token so it logs the user out once the cookie is expired. login form or the homepage?
    – Bruno
    Jul 23 at 8:54

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

createCookieInHour: (cookieName, cookieValue, hourToExpire) => {
    let date = new Date();
    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


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 credentials config does this when provided

credentials: "include", // or "same-origin" or "omit"

Well, but how to use it

--- after installation this package ----

to get cookies:

import Cookie from 'react-native-cookie';

Cookie.get('url').then((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 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.


Use Js-cookie package

npm i js-cookie

import Cookies from 'js-cookie'

Cookies.set('auth', 'data') 

This npm package worked for me & far good as well

Your Answer

