Topic 44 of 48 · Full Stack Essentials

JavaScript Cookies

Lesson TL;DRTopic 7: JavaScript Cookies 📖 14 min read · 🎯 intermediate · 🧭 Prerequisites: jointquerynestedqueryfilteringdata, calculatelogicaloperationtableprint Why this matters Picture this: you log into a w...
14 min read·intermediate·javascript · cookies · browser-storage · session-management

Topic 7: JavaScript Cookies

📖 14 min read · 🎯 intermediate · 🧭 Prerequisites: joint-query-nested-query-filtering-data, calculate-logical-operation-table-print

Why this matters

Picture this: you log into a website, pick your dark mode, and add something to your cart — then you close the tab. You come back an hour later, and it still knows who you are. How? That's cookies at work. A JavaScript cookie is a tiny piece of text your browser saves and sends back to the same website every time you visit. Without cookies, every single page load forgets everything — no "welcome back," no saved preferences, no staying logged in. In this lesson we'll learn how to read, write, and delete these small but powerful records with JavaScript.

What You'll Learn

  • Understand what cookies are, their types, and when to use each
  • Create cookies with expiration dates and path restrictions using document.cookie
  • Read and parse individual cookie values from the browser's cookie string
  • Delete cookies by setting their expiration date to the past
  • Build a complete theme-preference example that persists across page loads

The Analogy

Think of cookies like the sticky notes a hotel concierge keeps behind the desk for repeat guests. When you check in for the first time, the concierge jots down your room preferences — extra pillows, late checkout, no wake-up calls — and tucks the note away. Next time you arrive, they pull out that note before you even say a word and everything is set up exactly how you like it. Session cookies are like notes written in pencil that get erased the moment you leave; persistent cookies are laminated cards that stay in the file for months. The hotel (your browser) holds the notes, but you (the website) wrote them — and only you can update or shred them.

Chapter 1: What Are Cookies?

Cookies are small text files that websites store on a user's browser to remember information across different sessions. They are used for purposes such as tracking user activity, storing preferences, and managing login sessions. Every cookie is a name=value pair with optional attributes controlling its lifetime, scope, and security.

Types of Cookies

  1. Session Cookies — Temporary cookies deleted when the browser is closed. No expiration date is set.
  2. Persistent Cookies — Remain on the user's device for a set period or until manually deleted. Require an expires or max-age attribute.
  3. Secure Cookies — Only transmitted over HTTPS, enhancing security on the wire.
  4. HttpOnly Cookies — Not accessible via JavaScript, which significantly reduces the risk of XSS attacks stealing cookie data.
AttributePurpose
expiresSets a UTC expiry datetime; cookie is removed after this date
max-ageSeconds until expiry (alternative to expires)
pathURL path that must exist for the cookie to be sent
domainDomain (and subdomains) that can receive the cookie
secureRestricts cookie to HTTPS connections
HttpOnlyPrevents JavaScript access (set server-side)
SameSiteControls cross-site request behaviour (Strict, Lax, None)
flowchart LR
    Browser -->|sends request| Server
    Server -->|Set-Cookie header| Browser
    Browser -->|stores in cookie jar| CookieJar[(Cookie Jar)]
    CookieJar -->|document.cookie read/write| JS[JavaScript]
    CookieJar -->|Cookie header on next request| Server

Chapter 2: Creating Cookies

Cookies are created by assigning a formatted string to document.cookie. Despite the assignment syntax, this appends or updates one cookie — it does not replace the entire cookie jar.

// Create a simple cookie
document.cookie = "username=Alice";

Without an expiration date the cookie becomes a session cookie. To make it persistent, add the expires attribute in UTC format.

// 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;

The path attribute specifies which URL paths the cookie should accompany. Setting path=/ makes it available site-wide.

// Create a cookie scoped to the entire site
document.cookie = "username=Alice; path=/";

Reusable setCookie Helper

Rather than hand-building the string every time, wrap the logic in a utility function you can call anywhere in your application.

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=/";
}

// Store a username for 7 days
setCookie("username", "Alice", 7);

Chapter 3: Reading Cookies

The document.cookie property returns all cookies for the current page as a single semicolon-separated string, for example:

username=Alice; theme=dark; language=en

To extract a specific value you must split and search that string.

// Function to get the value of a specific cookie
function getCookie(name) {
    let cookieArr = document.cookie.split(";");

    for (let i = 0; i < cookieArr.length; i++) {
        let cookiePair = cookieArr[i].split("=");

        // trim() removes any leading whitespace before the cookie name
        if (name == cookiePair[0].trim()) {
            return decodeURIComponent(cookiePair[1]);
        }
    }

    // Return null if no matching cookie found
    return null;
}

// Example usage
let username = getCookie("username");

if (username) {
    console.log("Username: " + username);
} else {
    console.log("Username cookie not found");
}

Key points:

  • document.cookie.split(";") produces an array of name=value strings
  • .trim() on the name portion handles the space after each semicolon
  • decodeURIComponent() reverses any URL-encoding applied when the cookie was set (e.g. spaces stored as %20)

Chapter 4: Deleting Cookies

There is no dedicated delete API. To remove a cookie you overwrite it with an expiration date set in the past. The browser automatically discards expired cookies.

// Function to delete a cookie
function deleteCookie(name) {
    document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}

// Example usage
deleteCookie("username");

The epoch date Thu, 01 Jan 1970 00:00:00 UTC is the conventional "already expired" sentinel value used across virtually all cookie-deletion code. Including path=/ is important — a cookie set with path=/ can only be deleted if you delete with the same path.

Chapter 5: Practical Example — Remembering User Preferences

The class put all four operations together to build a theme-selector that persists the user's choice across page reloads.

HTML (index.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 given 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=/";
}

// Read a single named cookie from document.cookie
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;
}

// Delete a cookie by expiring it
function deleteCookie(name) {
    document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}

// Called by the <select> onchange — saves the choice and applies it immediately
function setTheme(theme) {
    setCookie("theme", theme, 7); // store for 7 days
    document.body.className = theme;
}

// On page load, read the saved theme and restore it
function loadTheme() {
    let theme = getCookie("theme");

    if (theme) {
        document.getElementById("theme").value = theme;
        document.body.className = theme;
    }
}

// Entry point
window.onload = loadTheme;

How the Data Flows

sequenceDiagram
    participant User
    participant Browser
    participant JS as script.js

    User->>Browser: Page loads
    Browser->>JS: window.onload fires
    JS->>Browser: document.cookie (read)
    Browser-->>JS: "theme=dark; ..."
    JS->>Browser: document.body.className = "dark"
    Browser-->>User: Page renders with dark theme

    User->>Browser: Changes select to "light"
    Browser->>JS: onchange → setTheme("light")
    JS->>Browser: document.cookie = "theme=light; expires=...; path=/"
    JS->>Browser: document.body.className = "light"
    Browser-->>User: Theme switches instantly

🧪 Try It Yourself

Task: Build a "visit counter" cookie that increments each time the user loads the page and displays the count in an <h2> tag.

Success criterion: Reload the page several times — the number in the heading should go up by 1 on every reload and survive a tab close/reopen (because it's persistent, not session-only).

Starter snippet:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Visit Counter</title>
</head>
<body>
    <h2 id="counter">Loading...</h2>
    <script>
        function setCookie(name, value, days) {
            let d = new Date();
            d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
            document.cookie = name + "=" + value + "; expires=" + d.toUTCString() + "; path=/";
        }

        function getCookie(name) {
            let parts = document.cookie.split(";");
            for (let p of parts) {
                let [k, v] = p.split("=");
                if (k.trim() === name) return decodeURIComponent(v);
            }
            return null;
        }

        // TODO: read "visits" cookie, increment it, save it back, update the <h2>
        // Hint: parseInt(getCookie("visits") || "0") + 1
    </script>
</body>
</html>

🔍 Checkpoint Quiz

Q1. What distinguishes a session cookie from a persistent cookie?

A) Session cookies are encrypted; persistent cookies are not B) Session cookies are deleted when the browser closes; persistent cookies survive until their expiry date or manual deletion C) Session cookies can only be set server-side D) Persistent cookies cannot be read by JavaScript

Q2. Given the following code, what does getCookie("color") return if document.cookie is "theme=dark; color=blue; lang=en"?

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;
}

A) "color=blue" B) null C) "blue" D) undefined

Q3. What is wrong with this cookie deletion attempt?

document.cookie = "username=; path=/dashboard;";

A) You cannot delete a cookie using document.cookie B) The cookie value must be null, not an empty string C) The expires attribute set to a past date is missing — without it, the cookie is merely updated, not deleted D) The path value is incorrect syntax

Q4. You want to store a user's language preference ("fr") that persists for 30 days and is available across the whole site. Which call is correct?

A) document.cookie = "lang=fr"; B) setCookie("lang", "fr", 30); — where setCookie sets expires 30 days ahead and path=/ C) localStorage.setItem("lang", "fr"); D) sessionStorage.setItem("lang", "fr");

A1. B — Session cookies have no expires attribute and are purged when the browser session ends; persistent cookies carry an expires or max-age and survive restarts until that date.

A2. C — "blue". The function splits on ";", then on "=", trims whitespace from the name, and returns decodeURIComponent of the matching value. " color" becomes "color" after .trim(), so it matches and returns "blue".

A3. C — To delete a cookie you must set its expires to a past date (e.g. Thu, 01 Jan 1970 00:00:00 UTC). Without expires, the line just overwrites the cookie's value to an empty string but leaves it alive.

A4. B — setCookie("lang", "fr", 30) with path=/ is the correct approach. Option A creates a session-only cookie with no path guarantee. C and D use Web Storage, not cookies, and don't send with HTTP requests.

🪞 Recap

  • Cookies are name=value text pairs stored in the browser, sent with every matching HTTP request, and readable via document.cookie in JavaScript.
  • The four key types are session, persistent, secure, and HttpOnly — each serving different lifetime and security needs.
  • Creating a cookie means assigning a formatted string to document.cookie; adding expires makes it persistent, and path=/ makes it site-wide.
  • Reading cookies requires splitting document.cookie on ";" and then on "=", trimming whitespace, and using decodeURIComponent on values.
  • Deleting a cookie means re-setting it with expires=Thu, 01 Jan 1970 00:00:00 UTC — the browser discards any cookie whose expiry has passed.

📚 Further Reading

Like this topic? It’s one of 48 in Full Stack Essentials.

Block your seat for ₹2,500 and join the next cohort.