133

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?

buydadip
  • 8,890
  • 22
  • 79
  • 154
OPfan
  • 1,625
  • 2
  • 13
  • 18

11 Answers11

242

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
speckledcarp
  • 6,196
  • 4
  • 22
  • 22
55

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

Smakosh
  • 1,034
  • 12
  • 13
21

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!

Oleksii Zymovets
  • 690
  • 8
  • 14
  • 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 '21 at 08:54
18

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});
};
bdougie
  • 751
  • 1
  • 7
  • 17
  • 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. – speckledcarp Apr 28 '17 at 15:37
16

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.

sergioviniciuss
  • 4,596
  • 3
  • 36
  • 50
  • 3
    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! – Mahdieh Shavandi Oct 27 '20 at 07:27
15

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

Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
  • 2
    Good solution - use standard JS API instead of additional dependency. See https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie for full documentation of the document.cookie API. – Cornflex Oct 21 '21 at 15:35
8

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) => {
   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);
});
Noushad
  • 6,063
  • 3
  • 25
  • 28
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
8

just use react-cookie library:

npm install react-cookie

index.js:

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

USAGE:

React hooks:

import React from "react";
import { useCookies } from "react-cookie";

export default function App() {
  const [cookies, setCookie] = useCookies(["user"]);

  function handleCookie() {
    setCookie("user", "gowtham", {
      path: "/"
    });
  }
  return (
    <div className="App">
      <h1>React cookies</h1>
      <button onClick={handleCookie}>Set Cookie</button>
    </div>
  );
}

class-based components:

import React, { Component } from "react";
import { instanceOf } from "prop-types";
import { withCookies, Cookies } from "react-cookie";

class App extends Component {
  static propTypes = {
    cookies: instanceOf(Cookies).isRequired
  };

  state = {
    user: this.props.cookies.get("user") || ""
  };

  handleCookie = () => {
    const { cookies } = this.props;
    cookies.set("user", "gowtham", { path: "/" }); // setting the cookie
    this.setState({ user: cookies.get("user") });
  };

  render() {
    const { user } = this.state;
    return (
      <div className="App">
        <h1>React cookies</h1>
        {user && <p>{user}</p>}
        <button onClick={this.handleCookie}>Set Cookie</button>
      </div>
    );
  }
}

export default withCookies(App);
Raskul
  • 1,674
  • 10
  • 26
5

Use Js-cookie package

npm i js-cookie

import Cookies from 'js-cookie'

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

This npm package worked for me & far good as well

Rohan Tomar
  • 427
  • 4
  • 13
1

The Document property cookie lets you read and write cookies associated with the document. It serves as a getter and setter for the actual values of the cookies.

document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; SameSite=None; Secure";

Know more

MD SHAYON
  • 7,001
  • 45
  • 38
0

Install npm install react-cookie

Syntax const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);

Parameter Cookies: Javascript object with all of the user’s cookies. setCookie: Function to set the cookies. removeCookie: Function to remove the cookies.

Example index.jsx

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

    ReactDOM.render(
       <CookiesProvider>
          <App />
       </CookiesProvider>,
       document.getElementById('root')
    );

App.jsx

    import React, { useState } from 'react';
    import { useCookies } from 'react-cookie';

    const App = () => {
       const [name, setName] = useState('');
       const [pwd, setPwd] = useState('');
       const [cookies, setCookie] = useCookies(['user']);

       const handle = () => {
          setCookie('Name', name, { path: '/' });
          setCookie('Password', pwd, { path: '/' });
       };
       return (
          <div className="App">
          <h1>Name of the user:</h1>
          <input
             placeholder="name"
             value={name}
             onChange={(e) => setName(e.target.value)}
          />
          <h1>Password of the user:</h1>
          <input
             type="password"
             placeholder="name"
             value={pwd}
             onChange={(e) => setPwd(e.target.value)}
          />
          <div>
             <button onClick={handle}>Set Cookie</button>
          </div>
       </div>
       );
    };
    export default App;