Cookies are small data strings stored in the user's browser. They are often used to remember information across pages or between visits, such as login sessions, theme preferences, or shopping cart contents.
In JavaScript, cookies are managed using the document.cookie property, which lets you create, read, update, and delete cookies for the current site.
expires or max-age attribute; it survives across browser sessions.expires, path, Secure, and SameSite that control cookie lifetime and scope.The basic syntax for setting a cookie in JavaScript is:
document.cookie = "name=value";
You can add attributes to control the cookie's behavior:
expires=<date-string> – date and time after which the cookie will be deleted.max-age=<seconds> – lifetime of the cookie in seconds.path=/ – makes the cookie available across the entire site.| Action | Syntax |
|---|---|
| Create | document.cookie = "key=value" |
| Read | document.cookie |
| Update | Set again using the same key |
| Delete | Set expires to a past date |
document.cookie = "username=JohnDoe";
expires
document.cookie = "username=JohnDoe;expires=Fri, 31 Dec 2025 23:59:59 UTC;path=/";
console.log(document.cookie);
// Example output:
// "username=JohnDoe; theme=dark"
document.cookie = "username=JaneDoe";
document.cookie = "username=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;";
function setCookie(name, value, days) {
const d = new Date();
d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + d.toUTCString();
document.cookie = name + "=" + encodeURIComponent(value) + ";" + expires + ";path=/";
}
function getCookie(name) {
const cname = name + "=";
const decoded = decodeURIComponent(document.cookie);
const parts = decoded.split(";");
for (let c of parts) {
c = c.trim();
if (c.indexOf(cname) === 0) {
return c.substring(cname.length);
}
}
return "";
}
function deleteCookie(name) {
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;";
}
Below is a simple interactive example that stores your name in a cookie and shows a personalized greeting whenever you visit or reload the page.
This example uses
setCookie() and getCookie() to remember your name for a few days.How it works:
username=YourName with an expiry date.document.cookie, finds the username cookie, and shows a custom greeting if it exists.path=/ to make cookies accessible across your entire site.encodeURIComponent() when storing values that may contain spaces or special characters.localStorage or sessionStorage instead of cookies.JSON.stringify() and parse with JSON.parse() when reading.Secure and HttpOnly (set from the server).theme and toggle between dark/light mode based on its value when the page loads.visited=true cookie and show a welcome popup only for new visitors.