Alexcamostyle
Alexcamostyle

Reputation: 4383

Can you store commas with spaces inside of cookies?

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?

Upvotes: 4

Views: 3067

Answers (2)

Fagner Brack
Fagner Brack

Reputation: 2403

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.

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190976

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).

Upvotes: 4

Related Questions