99

I need to know if my user is connected or not. For that I want to read the cookies that I set in the server side with express-session :

app.use(session({
    secret: 'crypted key',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false } // Put true if https
}))
app.post('/connect_user', (req, res) => {
    req.session.cookie.username = req.body.username
    findUserData('username', req.body.username, req, (userData) => {
        req.session.cookie.id = userData.id
        req.session.cookie.username = userData.username
        res.redirect('/profil')
    })
})

I tried to use react-cookie but it doesn't work even though I copy-pasted the npm react-cookie docs example:

import React from 'react';
import Landing from './Landing';
import Home from './Home';
import Profil from './Profil';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { instanceOf } from 'prop-types';
import { Cookies } from 'react-cookie';

class App extends React.Component {
    static propTypes = {
        cookies: instanceOf(Cookies).isRequired
      };
     
      constructor(props) {
        super(props);
     
        const { cookies } = props;
        this.state = {
          username: cookies.get('username')
        };
      }
    render() {
        console.log(this.state.name) 
        let homePage = (!this.state.username) ? <Landing/> : <Home/>
        return (
            <Router>
                <div>
                    <Route exact path='/' component={homePage}></Route>
                    <Route path='/profil' component={Profil}></Route>
                </div>
            </Router>
        )
    }
}

export default App;

It's weird because document.cookie renders the correct result, but I don't know how handle it:

PHPSESSID=0nv9ic8h7pv2b63lu4v7eg3mop; user_id=21; username=Ugo; SL_G_WPT_TO=fr; SL_GWPT_Show_Hide_tmp=undefined; SL_wptGlobTipTmp=undefined

8 Answers 8

150

You can use js-cookie package and can install it using npm install js-cookie --save command.

import React from 'react';
import Cookies from 'js-cookie';

class App extends React.Component {
     this.state = {
        username: Cookies.get('username')
     }

//  more code....
}  

Documentation : https://github.com/js-cookie/js-cookie

NPM : https://www.npmjs.com/package/js-cookie

4
  • 1
    Why use an additional package if you can do it with Vanilla JS?
    – Andrea D_
    Commented Apr 18, 2023 at 10:13
  • 1
    @AndreaD_ because npm install is easier than understanding what you're doing
    – sherrellbc
    Commented Jul 30, 2023 at 5:00
  • Therein lies the problem... Commented Nov 11, 2023 at 12:10
  • 1
    @chaoskreator Why use Vanilla JS if you can do it more simply with an additional package? Commented Feb 8, 2024 at 15:41
40

There is no need for a third party npm package. You can use plain JS to extract the cookie. Here is a custom function for that:

function getCookie(key) {
  var b = document.cookie.match("(^|;)\\s*" + key + "\\s*=\\s*([^;]+)");
  return b ? b.pop() : "";
}
35

If all you want is to get the cookie value by key, I would suggest using plain javascript without any dependencies.

In this example, it gets the cookie value by the key "username" with the help of Regex.

let cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)username\s*\=\s*([^;]*).*$)|^.*$/, "$1");

https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Example_2_Get_a_sample_cookie_named_test2

2
  • 1
    Why do you suggest not using dependencies when using dependencies is much simpler? What downsides are there for using a dependency in this particular case? Commented Feb 8, 2024 at 12:57
  • The use of libraries has gotten completely out of control. People can't be bothered to think for a second about doing any work. Now it's normal to create the simplest app you have like a 1000 node modules. Ridiculous. Downsides? What about lack of control, lack of understanding, rotten brain for not doing any effort for anything, just mindless consumption of libraries. Just another sign of the times... Commented Mar 14 at 20:59
22

I'd recommend using universal-cookie as its simpler to use. Mind you, cookies have nothing to do with React. They are stored on the browser and you could use the browser's default API to get cookies.

Here is an example how you can use universal-cookies

import React from 'react';
// other imports...
import Cookies from 'universal-cookie';

const cookies = new Cookies();

class App extends React.Component {
     this.state = {
        username: cookies.get('username')
     }

//  more code....   

Source: https://www.npmjs.com/package/universal-cookie

4
  • 2
    why do people keep adding this??? class App extends React.Component { this is not present in real code
    – uberrebu
    Commented Aug 24, 2021 at 9:57
  • @uberrebu you don't need this.state = {. That was just an example of how to use Cookies. Instead of this.state, you can do: const myCookieData = cookies.get('username')` Commented Aug 24, 2021 at 13:04
  • 2
    @uberrebu it was in 2018 when the answer was written. That's the way components where declared before functional components and hooks where commonplace Commented Mar 16, 2023 at 8:19
  • 1
    @uberrebu looks like your standard class component to me... Commented Nov 11, 2023 at 12:12
16

You can also use the method below without any 3rd party package as documented in developer.mozilla.org :

const cookieValue = document.cookie
  .split('; ')
  .find((row) => row.startsWith('YOUR-COOKIE='))?
  .split('=')[1];
1
  • 2
    A better version that doesn't trigger any exception, and instead returns undefined if the cookie doesn't exist: document.cookie.split('; ').filter(row => row.startsWith('cookie_name=')).map(c=>c.split('=')[1])[0] Commented May 29, 2022 at 15:29
13

If you have a cookie with "httpOnly:true" property, you can't access it with document.cookie. It might be the reason you have failed to access the cookie with these methods.

5

I hope this function may help:

function getCookie(name) {
  if (document.cookie && document.cookie !== '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i].trim();
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}
-1
cookie = key=>((new RegExp((key || '=')+'=(.*?); ','gm')).exec(document.cookie+'; ') ||['',null])[1]
console.log(cookie('test'))
2
  • 3
    On Stack Overflow, the how is important, but a great part of the quality level of the site comes from the fact that people go to great lengths to explain the why. While a code-only answer get the person who asked the question past whatever hurdle they might be facing, it doesn't do them or future visitors much good in the long run. See Is there any benefit in code-only answers?
    – Steve
    Commented Nov 2, 2021 at 13:19
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂
    – nima
    Commented Nov 2, 2021 at 15:12

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.