Cookies in JS
Cookies are small text files that are stored on the user's device by a web browser. They are used to store data that can be accessed by the web application. Cookies are typically used to store user preferences, session information, and other data that is needed to personalize the user experience. In JavaScript, cookies can be set, read, and deleted using the document.cookie property. This property returns a string that contains all the cookies that have been set for the current document. The document.cookie property can be used to set a cookie by assigning a string value to it.
Structure of a Cookie:
key=value; Expires=DATE; Path=/; Domain=example.com; Secure; SameSite=Strict
Example:
username=John; Expires=Wed, 09 Jul 2025 12:00:00 UTC; Path=/
Cookies Attributes
Attribute |
Description |
expires |
When the cookie should expire |
max-age |
Alternative to expires, in seconds |
path |
URL path the cookie is valid for |
domain |
Domain that can access the cookie |
secure |
Cookie only sent over HTTPS |
httponly |
Only sent with HTTP(S), inaccessible to JS |
Why Use encodeURIComponent?
Cookies are stored as plain strings in the format:
But:
If your key or value has spaces or special characters (e.g., = ; , % & ?), this can break your cookie string.
These characters have special meanings in HTTP headers or may cause parsing issues.
So, we use:
encodeURIComponent(value) when setting the cookie
decodeURIComponent(value) when reading the cookie
encodeURIComponent("John Doe@site.com");
// Output: "John%20Doe%40site.com"
It escapes all characters that are not safe in a URI (and thus, in cookies):
Replaces spaces with %20
Replaces @ with %40
Replaces &, ;, =, ?, etc.
Limitations of Cookies
Size: ~4KB max per cookie
Count: ~20-50 per domain (browser-dependent)
Performance: Sent with every request, so can slow things down if overused