Reputation: 1932
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 ?
Upvotes: 0
Views: 16606
Reputation: 11
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.
Upvotes: 1
Reputation: 1113
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')
Upvotes: 2