How to access a browser cookie in a react app

Viewed 48019

This question is a bit popular but Im not having such luck. Im mostly a backend person so Im learning as I go along.

I have a cookie named connect.sid and value of 12345. I see this in my chrome dev tools.

In my react app I console logged document.cookie and localStorage.getItem('connect.sid'). Im getting null values. How to get the value of 12345?

Passportjs, using passport-github2 strategy, created this cookie. I need access to it so I could talk to my API.

Thanks

5 Answers

Full example using the react-cookie v2.

You need to wrap your root component in and also the individual components where you want to access the cookies in withCookies(..). The cookies are then part of props.

client.js:

import {CookiesProvider} from "react-cookie";

<CookiesProvider>
  <App />
</CookiesProvider>

App.js:

import React from "react";
import {withCookies} from 'react-cookie';

class App extends React.Component {
  render() {
    const {cookies} = this.props;
    return <p>{cookies.get('mycookie')}</p>
  }
}

export default withCookies(App);

You should be able to access cookies by using document.cookie even while using passportjs on the backend from a react app. I was able to access document.cookies using passport-local strategy with a react app. There is no need for installing react-cookie.

Once you've fixed that problem, then you can simply split the cookies like the following example below, and dynamically retrieve your desired cookie:

const cookies = document.cookie.split(';');

for (let i = 0; i < cookies.length; i++) {
  if (cookies[i].startsWith('connect.sid=s%3A')) {
    //.. Do what you want with connect.sid cookie
    break;
  }
}
Related