orc13a
orc13a

Reputation: 107

Can't access cookies on client side | NodeJS and JS

Server-side code:

res.cookie('test', 'value', { expire: 400000 + Date.now(), httpOnly: false });
res.writeHead(302, {
  'Location': 'localhost:4000/test',
});
res.end();

Client-side code:

When I have console.log(document.cookie); Then I can see the cookie in the console in dev tools
When I try to get one cookie console.log(document.cookie.test); or console.log(document.cookie['test']);

Then I get undefined

Upvotes: 1

Views: 868

Answers (1)

kat1330
kat1330

Reputation: 5332

This is expected behavior. You are doing correct on server side.

On other side in browser cookie is saved as string separated by semi column. Each cookie contains key value pair separated by =.

In your case cookie will be like in following format:

"test=value"

If you add cookie "test2" and value "value2" you will have following format:

"test=value; test2=value2"

If you want to get value based cookie name you have to implement function which will parse string and extract value manually.

Please refer to following answer for more details.

Here is getCookie function implementation from W3Schools (this is only example, it is not tested or implemented by me):

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

Upvotes: 3

Related Questions