Cookies
Cookies are small pieces of data stored on the user’s browser. They are used to remember information between page loads or visits, such as login status, preferences, or tracking data. JavaScript can create, read, and delete cookies via the document.cookie
property.
Cookies are part of the Browser Object Model (BOM) and are accessible through the document
object.
Setting a Cookie
You can create a cookie by assigning a string to document.cookie
.
The format is:
cookieName=cookieValue; expires=date; path=path; domain=domain; secure
Example:
// Set a simple cookie
document.cookie = "username=Alice";
// Set a cookie with expiry date (1 day)
const date = new Date();
date.setTime(date.getTime() + (24*60*60*1000)); // 1 day in milliseconds
document.cookie = `username=Alice; expires=${date.toUTCString()}; path=/`;
Reading Cookies
All cookies accessible to the page are stored in document.cookie
as a semicolon-separated string.
Example:
console.log(document.cookie);
// Output: "username=Alice; theme=dark"
To retrieve a specific cookie:
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(";").shift();
return null;
}
console.log(getCookie("username")); // Output: Alice
Deleting a Cookie
To delete a cookie, set its expiration date to a past date.
Example:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
Practical Examples
Example 1 – Setting a Theme Cookie:
function setTheme(theme) {
const date = new Date();
date.setTime(date.getTime() + (30*24*60*60*1000)); // 30 days
document.cookie = `theme=${theme}; expires=${date.toUTCString()}; path=/`;
}
// Usage
setTheme("dark");
Example 2 – Checking a Cookie:
function checkTheme() {
const theme = getCookie("theme");
if (theme) {
document.body.className = theme;
} else {
document.body.className = "light";
}
}
checkTheme();
Example 3 – Deleting a Cookie on Logout:
function logout() {
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
alert("You have been logged out!");
}