1

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

orc13a
  • 97
  • 10
  • 1
    `document.cookie` returns a semi-colon separated string. Reading a cookie by name takes more work: https://stackoverflow.com/questions/5639346/what-is-the-shortest-function-for-reading-a-cookie-by-name-in-javascript – Turnip Nov 25 '19 at 18:08
  • 1
    Where exactly have you seen this paradigm for accessing cookie values? The [relevant MDN page for `document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) clearly documents `document.cookie` as "*a string containing a semicolon-separated list of all cookies (i.e. key=value pairs).*" – esqew Nov 25 '19 at 18:08
  • Possible duplicate of [How do I create and read a value from cookie?](https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie) – Turnip Nov 25 '19 at 18:11

1 Answers1

3

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 "";
}
kat1330
  • 5,134
  • 7
  • 38
  • 61