137

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?

13 Answers 13

256

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
Sign up to request clarification or add additional context in comments.

Comments

64

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

Comments

23

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 --save
    
  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!

1 Comment

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

1 Comment

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.
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.

1 Comment

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!
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

1 Comment

Good solution - use standard JS API instead of additional dependency. See developer.mozilla.org/en-US/docs/Web/API/Document/cookie for full documentation of the document.cookie API.
9

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

Comments

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

Comments

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

Comments

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

Comments

1

If you're are looking for a solution without depending on any 3rd party package, this snippet works well in React 18+:

import {useEffect, useState} from 'react';

export function useCookie(key, initial) : [string, (value: string) => any] {
    const [value, setValue] = useState(
        document.cookie.split('; ').find(row => row.startsWith(`${key}=`))?.split('=')[1] ?? initial
    );

    function setCookie(value) {
        document.cookie = `${key}=${value}; path=/; expires=Fri, 31 Dec 9999 23:59:59 GMT; SameSite=Lax;`;
    }

    useEffect(() => {
        setCookie(value);
    }, [value, key]);

    return [
        value,
        value => {
            setCookie(value);
            setValue(value);
        },
    ];
}

You can then use this function to create a persistent state variable which can be accessed from both sides, the server and the client:

import React from 'react';
import {useCookie} from './cookie';

export default function MyComponent(props) {
    …
    [myValue, setMyValue] = useCookie('cookie-key', 'initial-value');
    …
    return (
        <>
            …
        </>
    );
}

When invoking fetch(), that cookie value is then sent to the server.

Comments

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;

Comments

0

If you don't mind setting it from the client side, this method works pretty well in Next.js

  function setCookie(cookieName: string, cookieValue: string): string | undefined {
    const year = 60 * 60 * 24 * 365;
    document.cookie = `${cookieName}=${cookieValue}; max-age=${year}; path=/; SameSite=Lax; Secure;`;

    const cookie = document.cookie
      .split("; ")
      .find((row) => row.startsWith(cookieName))
      ?.split("=")[1];
    return cookie;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.