Cookies in JavaScript
Cookies
A JavaScript cookie is a piece of data stored in small text files, on our computer to be accessed by our web browser. In many situations, using cookies is the most useful and efficient way of remembering user data like tracking preferences, purchases, commissions, and other information which is required for better user experience. Cookies has 5 variable-length fields, which include following-
Name:- It is used to set and retrieved the cookies using key name and its value.
Expires or max-age:- It is used to set the expiry date and time for cookies. If a cookie doesnâ€â„¢t contain one of these options, it disappears when the browser is closed.
Domain:- It is used to set the domain name for the cookies.
Path:- It is used to set the path for the cookies. Once the path sets the cookie will be accessible for pages under that path. If a cookie doesnâ€â„¢t contain path option, then it will take the current path.
Secure:- If the cookie contains the word "secure", then cookie may only be retrieved or fetched with a secure server. If a cookie doesnâ€â„¢t contain "secure" option, then no such restriction exists.
Creating a Cookie
A cookie can be easily created using document.cookie in JavaScript like below-
document.cookie = "Cookie_name = Cookie_value; expires = Wed, 21 Aug 2019 21:00:00 UTC; path = /"
Updating a Cookie
A cookie can be easily updated using document.cookie in JavaScript like below-
document.cookie = "Cookie_name = Cookie_value; expires = Wed, 27 Nov 2019 23:00:00 UTC; path = /"
The old cookie will be overwritten bye new cookie.
Retrieving a Cookie
A cookie can be easily retrieved using document.cookie in JavaScript like below-
const cookies = document.cookie;
In JavaScript document.cookie will return all the available cookies in one string, like- cookie1 = value; cookie2 = value; cookie3 = value;
Deleting a Cookie
To delete a cookie, just set the value of the cookie to empty and expires parameter to a passed date.
document.cookie = "Cookie_name = ; expires = Thu, 01 Jan 1970 00:00:00 UTC; path = /"
Cookie Helper Functions
Working with document.cookie directly can be cumbersome. Here are reusable helper functions for setting, getting, and deleting cookies.
// Set a cookie with optional expiry days
function setCookie(name, value, days = 7) {
const expires = new Date();
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/;SameSite=Lax`;
}
// Get a cookie by name
function getCookie(name) {
const key = encodeURIComponent(name) + '=';
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
cookie = cookie.trim();
if (cookie.startsWith(key)) {
return decodeURIComponent(cookie.substring(key.length));
}
}
return null;
}
// Delete a cookie
function deleteCookie(name) {
document.cookie = `${encodeURIComponent(name)}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/`;
}
// Usage
setCookie('username', 'Alice', 30);
console.log(getCookie('username')); // Alice
deleteCookie('username');
console.log(getCookie('username')); // null
Cookies vs localStorage vs sessionStorage
| Feature | Cookies | localStorage | sessionStorage |
|---|---|---|---|
| Capacity | ~4KB | ~5-10MB | ~5-10MB |
| Sent to server | Yes (every request) | No | No |
| Expiry | Configurable | Never (manual) | Tab close |
| Accessible from | JS + Server | JS only | JS only |
| Use case | Auth tokens, tracking | User preferences | Temp session data |
- Cookies are sent with every HTTP request - keep them small to avoid performance overhead.
- Always set the path attribute to / unless you need to restrict the cookie to a specific path.
- Use SameSite=Lax or SameSite=Strict to protect against CSRF attacks.
- Add the Secure flag to ensure cookies are only sent over HTTPS.
- Use HttpOnly flag (server-side) to prevent JavaScript from accessing sensitive cookies like auth tokens.
- For larger client-side storage, prefer localStorage or sessionStorage over cookies.