0

I have a cookie on my browser and I want to read it with react, I use it like that:

import Cookies from 'js-cookie';
console.log(Cookies.get('cookieName1'));

when I run it, I get undefined on the console, but, the cookieName1 have a value on my cookies.

How can I fix it ?

13
  • 1
    can your print just Cookies.get(); and show us what you see there...? Commented Aug 13, 2019 at 14:14
  • 3
    Are you sure the cookie is visible to JavaScript? A cookie set by a server can be marked as HttpOnly which means that it is not visible from JavaScript Commented Aug 13, 2019 at 14:14
  • Can you run console.log(document.cookie) and tell us what you get. Commented Aug 13, 2019 at 14:20
  • @ArupRakshit it return undefined Commented Aug 13, 2019 at 14:22
  • 3
    @CodeLover Show us what you see there in developer tools. All the properties of the cookies Commented Aug 13, 2019 at 14:55

2 Answers 2

2

I have used js-cookies which works well.

import cookies from "js-cookies";

const secure = window.location.protocol === 'https'

to set value in cookie use below code

cookies.setItem("API_TOKEN", "hello", undefined, "/", undefined, secure)

to get value from cookie use below code

cookies.getItem("API_TOKEN")

to remove cookie use below code

cookies.removeItem('API_TOKEN')
Sign up to request clarification or add additional context in comments.

1 Comment

js-cookie 3.0.1 uses get instead of getItem.
1

if a cookie is marked as HttpOnly, it is not accessible on the client-side using JavaScript. The HttpOnly flag is a security feature for cookies that restricts them from being accessed by client-side scripts. This is done to mitigate the risk of cross-site scripting (XSS) attacks, where an attacker injects malicious scripts into a website, and those scripts attempt to steal sensitive information, such as cookies.

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.