Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a browser cookie in a react app

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

like image 726
Sylar Avatar asked May 22 '17 08:05

Sylar


2 Answers

Using react-cookie may be the easiest way to get cookie value. You can run npm install react-cookie, the v2 will be installed. If you only want to use a simple API only on the client, i will suggest to use v1. Just run npm install [email protected], add import cookie from 'react-cookie' to you file and use cookie.load('connect.sid') to get cookie value. You can check the README of v1 for detail.

If you still cannot get the cookie value, please confirm:

  1. the cookie is set to correct path like /, if you want your cookie to be accessible on all pages.
  2. the cookie is not httpOnly cookie, HttpOnly cookies aren't accessible via JavaScript.
like image 84
tony.hokan Avatar answered Oct 22 '22 08:10

tony.hokan


I know that answer is not exactly what you want, but if you just want to authorize someone on the serverside i have an easy solution. Just add

credentials: 'same-origin'

to your AJAX request. If you have done that the cookie will get send with your connect.sid to the server and the server will handle the authentification for you.

like image 26
NotGapsong Avatar answered Oct 22 '22 09:10

NotGapsong