Topic 7: JavaScript Cookies
📖 6 min read · 🎯 Advanced · 🧭 Prerequisites: div-page-design, javascript-validation
Why this matters
Here's the thing — you've probably noticed that websites remember you. You visit an online store, close the tab, come back the next day, and your cart is still there. Or a site greets you by name without asking you to log in again. How does that happen?
That's cookies at work. A cookie is just a small note your browser keeps for a website — so the next time you visit, the site can read that note and pick up where it left off. Today we're going to learn how JavaScript writes those notes using document.cookie, how to read them back, and how to delete them when you're done.
What You'll Learn
- Understand the four types of cookies and when to use each
- Create cookies with expiration dates and path restrictions
- Parse the
document.cookiestring to read individual values - Delete cookies by setting their expiration to a past date
- Build a working theme-preference system backed by cookies
The Analogy
Think of cookies like the coat-check tickets at a Vizag jazz club. When you arrive, the attendant hands you a small numbered ticket — that's the cookie stored in your browser. The next time you walk in, you hand over the ticket and the attendant retrieves exactly your coat (your preferences, your session). The ticket has a printed expiry: some are good for one night only (session cookies), others for a whole season (persistent cookies). The club can also issue VIP tickets that are only valid at the main entrance (path-restricted cookies) or security-stamped ones that can't be photocopied by a pickpocket (HttpOnly cookies). The ticket is small — it holds just enough information to fetch the right coat, nothing more.
Chapter 1: What Are Cookies?
Cookies are small text files that a website stores in a user's browser to remember information across different sessions. They travel back to the server on every matching HTTP request, and they're also readable (and writable) from JavaScript via document.cookie.
Types of Cookies
- Session Cookies — Temporary cookies deleted automatically when the browser closes.
- Persistent Cookies — Remain on the user's device for a defined period or until manually deleted. Require an
expiresormax-ageattribute. - Secure Cookies — Transmitted only over HTTPS, preventing interception on plain HTTP connections.
- HttpOnly Cookies — Not accessible via JavaScript at all; set by the server to reduce the risk of XSS attacks stealing session tokens.
graph TD
A[Browser makes request] --> B{Cookie match?}
B -- Yes --> C[Attach cookie header to request]
B -- No --> D[Request sent without cookie]
C --> E[Server reads cookie]
E --> F[Server responds]
F --> G{Set-Cookie header?}
G -- Yes --> H[Browser stores/updates cookie]
G -- No --> I[Browser uses existing cookie]
Chapter 2: Creating Cookies
Cookies are created by assigning a string to document.cookie. Despite looking like a single property, each assignment adds or updates one cookie — it does not overwrite the entire cookie jar.
Basic Cookie Creation
// Create a simple cookie
document.cookie = "username=Alice";
Cookie with Expiration Date
Without an expires attribute, a cookie is a session cookie and disappears when the browser closes. Add an expiry to make it persistent.
// Create a cookie that expires in 7 days
let date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days in milliseconds
let expires = "expires=" + date.toUTCString();
document.cookie = "username=Alice; " + expires;
Cookie with Path
The path attribute restricts which URLs on the domain will send the cookie. Setting path=/ makes the cookie available site-wide.
// Create a cookie accessible on every page of the site
document.cookie = "username=Alice; path=/";
Chapter 3: Reading Cookies
Reading cookies is the trickiest part. document.cookie returns all cookies as one semicolon-separated string like "username=Alice; theme=dark; lang=en". You have to split and search that string yourself.
// Function to get the value of a specific cookie by name
function getCookie(name) {
let cookieArr = document.cookie.split(";");
for (let i = 0; i < cookieArr.length; i++) {
let cookiePair = cookieArr[i].split("=");
// Trim whitespace from the name before comparing
if (name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
// Return null if the cookie was not found
return null;
}
// Example usage
let username = getCookie("username");
if (username) {
console.log("Username: " + username);
} else {
console.log("Username cookie not found");
}
Key details:
split(";")separates individual cookies.split("=")separates each cookie's name from its value..trim()removes the leading space that follows every semicolon in the raw string.decodeURIComponent()reverses any URL-encoding applied when the value was stored.
Chapter 4: Deleting Cookies
JavaScript has no direct "delete cookie" API. The trick is to overwrite the cookie with an expires date in the past — the browser then discards it immediately.
// Function to delete a cookie by setting its expiry to the Unix epoch
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
// Example usage
deleteCookie("username");
The value is left empty and the expiry Thu, 01 Jan 1970 00:00:00 UTC (Unix epoch) guarantees the browser treats the cookie as already expired and removes it.
Gotcha: The
pathin the delete call must match thepathused when the cookie was created. Deletingusernamewithoutpath=/when it was set withpath=/will silently fail.
Chapter 5: Practical Example — Remembering User Preferences
The class's showcase: a page that remembers which colour theme the user selected, even after they close and reopen the browser. The full setCookie, getCookie, and deleteCookie helpers are assembled into a single working flow.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Example</title>
</head>
<body>
<h1>Welcome to Vizag</h1>
<label for="theme">Choose a theme:</label>
<select id="theme" onchange="setTheme(this.value)">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js)
// Set a cookie with a name, value, and lifetime in days
function setCookie(name, value, days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
let expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + "; " + expires + "; path=/";
}
// Retrieve a cookie value by name; returns null if absent
function getCookie(name) {
let cookieArr = document.cookie.split(";");
for (let i = 0; i < cookieArr.length; i++) {
let cookiePair = cookieArr[i].split("=");
if (name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}
// Remove a cookie by expiring it immediately
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
// Save the selected theme to a cookie and apply it to the page
function setTheme(theme) {
setCookie("theme", theme, 7); // persists for 7 days
document.body.className = theme;
}
// On page load, restore the saved theme (if any)
function loadTheme() {
let theme = getCookie("theme");
if (theme) {
document.getElementById("theme").value = theme;
document.body.className = theme;
}
}
window.onload = loadTheme;
How it works end-to-end:
- User selects "dark" from the dropdown →
setTheme("dark")fires. setCookie("theme", "dark", 7)writestheme=dark; expires=<7 days from now>; path=/intodocument.cookie.document.body.className = "dark"applies the theme visually.- User closes and reopens the browser →
window.onloadcallsloadTheme(). getCookie("theme")finds"dark"in the cookie jar, syncs the<select>, and re-applies the class.
🧪 Try It Yourself
Task: Extend the preference example to also remember the user's font-size choice.
- Add a second
<select>to the HTML with optionssmall,medium,large. - Write a
setFontSize(size)function that saves the selection as a cookie named"fontSize"for 7 days and applies a corresponding CSS class todocument.body. - Update
loadTheme()(or rename itloadPreferences()) to also read the"fontSize"cookie and restore both the dropdown value and the body class on page load.
Success criterion: Close the browser tab, reopen it, and both the theme dropdown and the font-size dropdown should reflect the values you last selected — without any hardcoded defaults kicking in.
Starter snippet:
function setFontSize(size) {
setCookie("fontSize", size, 7);
document.body.classList.remove("small", "medium", "large");
document.body.classList.add(size);
}
🔍 Checkpoint Quiz
Q1. What is the key difference between a Session Cookie and a Persistent Cookie?
A) Session cookies are encrypted; persistent cookies are not
B) Session cookies are deleted when the browser closes; persistent cookies have an expires or max-age attribute
C) Session cookies can only be read server-side; persistent cookies are JavaScript-accessible
D) Session cookies require HTTPS; persistent cookies work on HTTP
Q2. Given the following code, what will console.log(result) print if the browser's cookie jar currently contains the string "lang=en; username=Bob; theme=dark"?
function getCookie(name) {
let cookieArr = document.cookie.split(";");
for (let i = 0; i < cookieArr.length; i++) {
let cookiePair = cookieArr[i].split("=");
if (name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}
let result = getCookie("username");
console.log(result);
A) "lang=en"
B) null
C) "Bob"
D) "username=Bob"
Q3. What is wrong with this cookie deletion attempt, given the cookie was originally set with path=/?
document.cookie = "session=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
A) The value should be null, not an empty string
B) The expires date format is wrong
C) The path=/ attribute is missing, so the browser won't match and delete the correct cookie
D) You cannot delete cookies from JavaScript at all
Q4. You are building a "remember me" feature. The user checks the box and logs in. How would you use cookies to keep the user's userId stored for 30 days?
A1. B — Session cookies have no expiry attribute and are purged when the browser session ends; persistent cookies carry an expires or max-age that tells the browser when to discard them.
A2. C — "Bob". The function splits on ";" to get ["lang=en", " username=Bob", " theme=dark"], trims the key of each pair, matches "username", and returns decodeURIComponent("Bob").
A3. C — The path in a delete call must match the path used during creation. Without path=/, the browser looks for a cookie scoped to the current directory path, finds no match, and the original cookie survives.
A4. Call setCookie("userId", theUserId, 30) after successful login — this writes a persistent cookie with an expiry 30 days from now. On subsequent page loads, call getCookie("userId") to check whether the user is still remembered without requiring a new login.
🪞 Recap
- Cookies are small browser-stored text files used for session management, preference storage, and activity tracking.
- The four cookie types — Session, Persistent, Secure, and HttpOnly — serve different security and lifetime needs.
- Create a cookie by assigning to
document.cookiewith optionalexpiresandpathattributes. - Reading cookies requires splitting the raw
document.cookiestring and trimming whitespace around each name. - Deleting a cookie means re-setting it with an expiry date in the past, using the same
pathas the original.
📚 Further Reading
- MDN Web Docs — document.cookie — the source of truth on the cookie API and all supported attributes
- MDN Web Docs — HTTP Cookies — deep dive into how cookies work at the HTTP level, including
SameSiteand security flags - OWASP — Testing for Cookies Attributes — security checklist for cookie hygiene in production apps
- ⬅️ Previous: JavaScript Validation
- ➡️ Next: Recreate Task External CSS