import Cookies from 'js-cookie';
//this returns null
const authTokenFromCookies = Cookies.get('authToken');
console.log("AuthToken from cookies:", authTokenFromCookies);
// This returns the token set from the backend
const authToken = response.headers['authToken'];
console.log("AuthToken after login:", authToken);
js-cookie returns null but headers return the set cookies, Why?
What could be the cause?
2
Answers
Because a cookie named
authToken
, and a response header namedauthToken
, are absolutely not the same thing.A cookie would be set via a
Set-Cookie
header. (A response headerSet-Cookie: authToken=value
would create a cookie namedauthToken
.)You did not log any actual cookie there in that second block, you logged the value of the header named
authToken
.Hope this answers your query.
It should be noted that
js-cookie
can only interact with cookies which are accessible by javascript.As @c3roe rightly mentioned, you are receiving
null
because there is no javascript-accessible cookie with the nameauthToken
.Debug Approach:
authToken
via devTools.httpOnly
cookie ( httpOnly cookies are inaccessible by javascript ).