Cookies are small pieces of data stored in the user's browser. They are commonly used to remember user preferences, maintain login sessions, store authentication tokens (carefully), and track user activity.
π What are Cookies?
A cookie is a small text value that a website stores in the browser. Every time the browser sends a request to the same website, the cookie is automatically included in the request (subject to its settings).
π‘ Why Use Cookies?
- π€ Remember logged-in users
- π Save language preferences
- π Store shopping cart information
- π¨ Save theme settings (Dark/Light mode)
- π Analytics and tracking
πͺ Cookie Syntax
Cookies are managed using the document.cookie property.
Basic Cookie Syntax
document.cookie = "username=John";The cookie is stored as a string in the browser.
π Creating a Cookie
Create Cookie
document.cookie = "username=John";This creates a session cookie, which is removed when the browser closes.
π Reading Cookies
Read Cookies
console.log(document.cookie);If multiple cookies exist, they are returned as a semicolon-separated string.
Example Output
username=John; theme=dark; language=enβοΈ Updating a Cookie
To update a cookie, assign a new value using the same cookie name.
Update Cookie
document.cookie = "username=Alice";ποΈ Deleting a Cookie
Cookies are deleted by setting their expiration date to a time in the past.
Delete Cookie
document.cookie =
"username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";β³ Cookie Expiration
You can specify how long a cookie should remain stored.
Cookie with Expiration
document.cookie =
"username=John; expires=Fri, 31 Dec 2027 23:59:59 UTC; path=/";Note
π Cookie Path
The path attribute controls where the cookie is accessible.
Cookie Path
document.cookie =
"theme=dark; path=/";Setting path=/ makes the cookie available across the entire website.
π Secure Cookies
Security attributes help protect cookies from unauthorized access.
| Attribute | Description |
|---|---|
| Secure | Sent only over HTTPS. |
| HttpOnly | Cannot be accessed by JavaScript (server-set only). |
| SameSite | Helps protect against CSRF attacks. |
Secure Cookie
document.cookie =
"theme=dark; Secure; SameSite=Strict";Note
π οΈ Helper Functions
Set Cookie
setCookie()
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie =
name +
"=" +
encodeURIComponent(value) +
"; expires=" +
date.toUTCString() +
"; path=/";
}Get Cookie
getCookie()
function getCookie(name) {
const cookies = document.cookie.split(";");
for (let cookie of cookies) {
const c = cookie.trim();
if (c.startsWith(name + "=")) {
return decodeURIComponent(c.substring(name.length + 1));
}
}
return null;
}Delete Cookie
deleteCookie()
function deleteCookie(name) {
document.cookie =
name +
"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
}π Example
Complete Example
setCookie("username", "John", 7);
console.log(getCookie("username"));
deleteCookie("username");π Cookie vs Local Storage vs Session Storage
| Feature | Cookies | Local Storage | Session Storage |
|---|---|---|---|
| Storage Limit | ~4 KB | ~5β10 MB | ~5 MB |
| Expires | Configurable | Never (until cleared) | Tab closes |
| Sent to Server | β Yes | β No | β No |
| Accessible by JS | Usually Yes | Yes | Yes |
β οΈ Best Practices
- π Use HTTPS with the Secure attribute.
- π‘οΈ Use SameSite=Lax or SameSite=Strict to reduce CSRF risk.
- π« Avoid storing sensitive data such as passwords in cookies.
- π¦ Keep cookie values small (typically under 4 KB).
- π Use server-set HttpOnly cookies for authentication tokens when possible.
- π§Ή Remove cookies that are no longer needed.
π― Summary
JavaScript cookies allow websites to store small amounts of information in the browser. You can create, read, update, and delete cookies usingdocument.cookie. While cookies are useful for sessions and user preferences, modern web applications often use localStorage orsessionStorage for client-side data that does not need to be sent with every HTTP request.