skip to Main Content
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


  1. js-cookie returns null but headers return the set cookies, Why?

    Because a cookie named authToken, and a response header named authToken, are absolutely not the same thing.

    A cookie would be set via a Set-Cookie header. (A response header Set-Cookie: authToken=value would create a cookie named authToken.)

    You did not log any actual cookie there in that second block, you logged the value of the header named authToken.

    Login or Signup to reply.
  2. 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 name authToken.

    Debug Approach:

    • Check if there is a cookie with name authToken via devTools.
    • If the cookie is available is it a httpOnly cookie ( httpOnly cookies are inaccessible by javascript ).
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search