4

Recently I've been playing around with cookies and I noticed that when I create one with a value of "Hello, World!", I get "Hello":

document.cookie = "testCookie=Hello, World!;";

Interestingly enough, if I don't add a space to "Hello, World!", the cookie's value remains as I set it: ("Hello,World!")

document.cookie = "testCookie=Hello,World!;";

My only guess as to why this happens is because a comma and a space ", " ends cookies like semicolons and spaces "; " do. Is this the case, or am I doing something wrong?

Alexcamostyle
  • 3,623
  • 4
  • 14
  • 13
  • 1
    You would want to put quotes around a string `"testCookie='Hello, World!';"` [MDN actually has a framework](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) that has `.setCookie` and `.getCookie` to use to avoid problems like that:. – Spencer Wieczorek Oct 23 '15 at 17:16
  • If you're going to interact with the raw `document.cookie` string, you should probably understand the structure a little better. – maček Oct 23 '15 at 17:18
  • *Note* in my last comment they should be `.getItem` and `.setItem`, my internet's been crashing so I wasn't able to edit it. – Spencer Wieczorek Oct 23 '15 at 17:23

2 Answers2

4

You should use encodeURIComponent on the value as MDN states:

The cookie value string can use encodeURIComponent() to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values).

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Thank you very much! It works perfectly. Also, it's worth noting for anyone who might need it that I used `decodeURIComponent` to display the cookie's value to the user more simplistically. – Alexcamostyle Oct 23 '15 at 20:52
  • It's not like you "should" use `encodeURIComponent`, but you "can" use it. `encodeURIComponent` also encodes characters that it should not to, so it all depends upon your use case. – Fagner Brack Oct 24 '15 at 18:37
0

See here for the characters that are allowed in the cookie, and also de RFC 6265 if you must.

In the cookie value:

In the cookie name (key)

Conclusion
All characters that you are trying to use in cookies are not allowed per spec, therefore you need to encode it if you want to ensure it works across all browsers, otherwise the behavior is undefined.

Recommendation
I recommend a project that me and Klaus Hartl maintain called js-cookie, it was previously called jquery.cookie, it tries to document and understand all browser-related limitations to provide a pattern that fix all these problems. It works with all unicode characters in the browser.

Community
  • 1
  • 1
Fagner Brack
  • 2,365
  • 4
  • 33
  • 69