Session 10
Javascript Cookies
Cookies are small text files stored on the user's client-side computer that allow web applications to "remember" information across page reloads or future visits. While modern web development often uses localStorage or sessionStorage for client-side persistence, cookies remain essential for session tracking, authentication tokens, and server-side state management because they are automatically sent with every HTTP request to the matching domain. Session 10 covers the complete lifecycle of cookies using the native document.cookie API, teaching you how to create, read, parse, modify, and delete them programmatically.
Objectives
- Understand how cookies work and their role in web state management
- Create, read, update, and delete cookies using document.cookie
- Parse the raw cookie string to extract specific name=value pairs
- Implement practical exercises for user preference storage and session tracking
What is a JavaScript Cookie?
- A cookie is a small piece of data stored as a name=value pair in the browser.
- Stored as plain text files on the client machine.
- Automatically included in Cookie HTTP headers for subsequent requests to the same domain/path.
Cookie Structure & Attributes
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2026 23:59:59 GMT; path=/; domain=example.com; secure; samesite=strict";
| Attribute | Purpose |
|---|---|
expires / max-age | Defines lifespan. If omitted, cookie is a session cookie (deleted when browser closes) |
path | Scope of the cookie. path=/ makes it available site-wide |
domain | Host scope. Default is current domain |
secure | Only sent over HTTPS |
samesite | CSRF protection (Strict, Lax, None) |
The document.cookie API
| Operation | Syntax | Behavior |
|---|---|---|
| Create/Update | document.cookie = "name=value; path=/" | Appends or overwrites existing cookie with same name |
| Read All | let all = document.cookie | Returns a single string: "id=1; theme=dark; user=John" |
| Delete | document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"; | Forces expiration to a past date |
Important:
document.cookiedoes not return an object or array. You must manually parse the string to extract specific values.
Parsing the Cookie String
function getCookie(name) {
const nameEQ = name + "=";
const cookies = document.cookie.split(';');
for(let i = 0; i < cookies.length; i++) {
let c = cookies[i].trim();
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length);
}
return null; // Not found
}
Best Practices & Limitations
| Limitation | Workaround / Best Practice |
|---|---|
| Size limit (~4KB per cookie) | Store only essential identifiers; use localStorage for bulk data |
| Sent with every request | Minimize cookie count & size for performance |
Accessible via JS (document.cookie) | Never store passwords/sensitive data; use HttpOnly (server-set only) for security-critical cookies |
| Parsing overhead | Use helper functions or modern cookie libraries in production |
Quick Guide
// ✅ Set Cookie
function setCookie(name, value, days) {
const d = new Date(); d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = `${name}=${value};expires=${d.toUTCString()};path=/`;
}
// 🔍 Get Cookie
function getCookie(name) {
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
return match ? decodeURIComponent(match[2]) : null;
}
// 🗑️ Delete Cookie
function deleteCookie(name) {
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`;
}
Question 1
Problem Statement
Create an HTML web page, as shown below. The cookie will be set on pressing setCookie button and the stored cookie value will be displayed on pressing getCookie button.
Note: Check lab manual for images
Demo
Set & Get Cookie
Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ex1: Set & Get Cookie</title>
<style>
body {
font-family: sans-serif;
padding: 20px;
max-width: 400px;
}
input,
button {
padding: 8px;
margin: 5px;
width: 100%;
}
</style>
</head>
<body>
<h3>Set & Get Cookie</h3>
<input id="cookieVal" type="text" placeholder="Enter cookie value" />
<button id="setBtn">Set Cookie</button>
<button id="getBtn">Get Cookie</button>
<p id="display" style="margin-top: 10px; font-weight: bold"></p>
<script>
function setCookie(name, value, days) {
const d = new Date();
d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${value};expires=${d.toUTCString()};path=/`;
}
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(";");
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim();
if (c.indexOf(nameEQ) === 0)
return c.substring(nameEQ.length);
}
return null;
}
document.getElementById("setBtn").onclick = () =>
setCookie(
"labCookie1",
document.getElementById("cookieVal").value,
30,
);
document.getElementById("getBtn").onclick = () =>
(document.getElementById("display").textContent =
getCookie("labCookie1") || "❌ No cookie found");
</script>
</body>
</html>
HTML View
Question 2
Problem Statement
Considering exercise 1, modify the web page to display the cookie's name-value pair separately as shown in figure below.
Note: Check lab manual for images/figures
Demo
All Cookies (Name-Value Pairs)
- No cookies found
Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ex2: Parse Cookies</title>
<style>
body {
font-family: sans-serif;
padding: 20px;
}
ul {
list-style: none;
padding: 0;
}
li {
background: #f4f4f4;
margin: 5px;
padding: 10px;
border-left: 4px solid #333;
}
</style>
</head>
<body>
<h3>All Cookies (Name-Value Pairs)</h3>
<button id="parseBtn" style="padding: 8px 16px; margin-bottom: 15px">
Parse & Display Cookies
</button>
<ul id="cookieList">
<li>No cookies yet</li>
</ul>
<script>
document.getElementById("parseBtn").onclick = () => {
const raw = document.cookie;
const list = document.getElementById("cookieList");
list.innerHTML = "";
if (!raw) {
list.innerHTML = "<li>No cookies found</li>";
return;
}
raw.split(";").forEach((pair) => {
const [name, value] = pair.split("=").map((s) => s.trim());
if (name)
list.innerHTML += `<li><strong>${name}:</strong> ${value}</li>`;
});
};
</script>
</body>
</html>
HTML View
Question 3
Problem Statement
A list of color is provided in the form of drop down list. The background color of the web page changes as per the selection of the color from the list by the user. At the same time the chosencoloris passed to the cookie. The cookie stores the last choice of a user in a browser which will be used on reloading the web page to display the same color as background color.
Note: Check lab manual for images/figures
Demo
Select Background Color (Persisted via Cookie)
Current: white
Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ex3: Color Cookie</title>
<style>
body {
font-family: sans-serif;
padding: 20px;
transition: background 0.3s;
}
select {
padding: 8px;
font-size: 16px;
}
</style>
</head>
<body>
<h3>Select Background Color (Persisted via Cookie)</h3>
<select id="colorSelect" onchange="applyColor(this.value)">
<option value="white">White</option>
<option value="#ffeb3b">Yellow</option>
<option value="#4caf50">Green</option>
<option value="#2196f3">Blue</option>
<option value="#9c27b0">Purple</option>
</select>
<script>
function setCookie(name, value, days) {
const d = new Date();
d.setTime(d.getTime() + days * 86400000);
document.cookie = `${name}=${value};expires=${d.toUTCString()};path=/`;
}
function applyColor(color) {
document.body.style.backgroundColor = color;
setCookie("bgColor", color, 365);
}
// Restore on load
window.onload = () => {
const match = document.cookie.match(/bgColor=([^;]+)/);
if (match) applyColor(match[1]);
};
</script>
</body>
</html>
HTML View
Question 4
Problem Statement
Create an HTML web page, as shown below. The cookie1 and cookie2 will be set on pressing Set Cookie1or Set Cookie2 button and the stored cookie value will be displayed on pressing Get Cookie1 or Get Cookie2 button respectively. On the other hand selectively cookie can be deleted by pressing Delete Cookie1 or Delete Cookie2 button. Display all cookies button will show all the stored cookies.
Note: Check lab manual for images/figures
Demo
Cookie Manager
Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ex4: Multi-Cookie Manager</title>
<style>
body {
font-family: sans-serif;
padding: 20px;
max-width: 500px;
}
input,
button {
padding: 8px;
margin: 4px;
}
.row {
display: flex;
gap: 5px;
margin-bottom: 10px;
}
pre {
background: #f4f4f4;
padding: 10px;
border-radius: 5px;
white-space: pre-wrap;
}
</style>
</head>
<body>
<h3>Cookie Manager (Cookie1 & Cookie2)</h3>
<div class="row">
<input id="val1" placeholder="Value for Cookie1" />
<button onclick="set('c1', 'val1')">Set C1</button>
<button onclick="get('c1')">Get C1</button>
<button onclick="del('c1')">Del C1</button>
</div>
<div class="row">
<input id="val2" placeholder="Value for Cookie2" />
<button onclick="set('c2', 'val2')">Set C2</button>
<button onclick="get('c2')">Get C2</button>
<button onclick="del('c2')">Del C2</button>
</div>
<button onclick="showAll()" style="margin-top: 10px; width: 100%">
Display All Cookies
</button>
<pre id="out">Ready...</pre>
<script>
function set(name, valId) {
if (!name || !valId) {
document.getElementById("out").textContent =
`Provide valid cookie${name[1]} value`;
return;
}
const v = document.getElementById(valId).value;
document.cookie = `cookie${name[1]}=${v};expires=Fri, 31 Dec 2027 23:59:59 GMT;path=/`;
document.getElementById("out").textContent =
`Set cookie${name[1]} = ${v}`;
}
function get(name) {
const match = document.cookie.match(
new RegExp(`(^| )cookie${name[1]}=([^;]+)`),
);
document.getElementById("out").textContent = match
? `cookie${name[1]} = ${match[2]}`
: `❌ cookie${name[1]} not found`;
}
function del(name) {
document.cookie = `cookie${name[1]}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`;
document.getElementById("out").textContent =
`Deleted cookie${name[1]}`;
}
function showAll() {
document.getElementById("out").textContent =
document.cookie || "No cookies stored";
}
</script>
</body>
</html>