A browser cookie is a small name/value string associated with a site. In JavaScript, cookies that are available to client-side code are read and written through document.cookie.
document.cookie = 'name=Simon';
const allCookies = document.cookie;
Do not store passwords, card numbers, authentication secrets, or other sensitive values in JavaScript-readable cookies. A cookie set from JavaScript also cannot use the HttpOnly attribute; sensitive session cookies should normally be set by the server.
The original tutorial starts with a simple name/value pair. That remains the basic form:
document.cookie = 'name=' + encodeURIComponent(name);
Cookie values should be encoded before storage when they may contain spaces or special characters. When reading the value, decode it with decodeURIComponent().
Without expires or max-age, a cookie is a session cookie. To keep it longer, provide an expiry date. This example keeps the original tutorial's one-day lifetime:
const expires = new Date();
expires.setDate(expires.getDate() + 1);
document.cookie = `name=${encodeURIComponent(name)}; expires=${expires.toUTCString()}; path=/javascript_tutorial; SameSite=Lax`;
The live Add Cookie demo intentionally uses a one-minute expiry, matching the original demo. Change the date calculation to control the lifetime.
path=/javascript_tutorial makes the cookie available to pages in this tutorial folder and also makes deletion predictable. SameSite=Lax is an appropriate default for this same-site learning example. Add Secure when the cookie should be sent only over HTTPS.
The expiry example still uses JavaScript's Date object, getDate(), setDate(), and toUTCString().
document.cookie returns all JavaScript-readable cookies for the current document as a semicolon-separated string. The original tutorial introduces these as JavaScript string operations and uses split(), indexOf(), and substr(). The same idea can be written more safely today by splitting, trimming, and checking the exact cookie-name prefix:
function getCookie(cookieName) {
const prefix = `${cookieName}=`;
const parts = document.cookie.split(';');
for (const part of parts) {
const cookie = part.trim();
if (cookie.startsWith(prefix)) {
return decodeURIComponent(cookie.slice(prefix.length));
}
}
return null;
}
Trimming matters because browsers typically separate cookie pairs with a semicolon followed by a space. Checking the prefix avoids accidental partial-name matches.
Delete a cookie by writing the same name and path with an expiry date in the past:
document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/javascript_tutorial; SameSite=Lax';
The path must match the path used when the cookie was created. Otherwise a different cookie can remain in place.
The original demo sequence is preserved: add a name, read the stored cookie, then delete it.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Add a JavaScript cookie</title>
</head>
<body>
<label for="name">Name</label>
<input type="text" id="name">
<button type="button" id="add-cookie">Add Cookie</button>
<p id="status" aria-live="polite"></p>
<nav><a href="add-cookies-demo.php">Add Cookies</a> | <a href="read-cookies-demo.php">Read Cookies</a> | <a href="delete-cookies-demo.php">Delete Cookies</a></nav>
<script>
const input = document.getElementById('name');
const status = document.getElementById('status');
document.getElementById('add-cookie').addEventListener('click', () => {
const name = input.value.trim();
if (!name) {
status.textContent = 'Enter a name first.';
return;
}
const expires = new Date();
expires.setDate(expires.getDate() + 1);
document.cookie = `name=${encodeURIComponent(name)}; expires=${expires.toUTCString()}; path=/javascript_tutorial; SameSite=Lax`;
status.textContent = 'Cookie added for one day.';
});
</script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Read a JavaScript cookie</title>
</head>
<body>
<p id="all-cookies"></p>
<p id="welcome"></p>
<nav><a href="add-cookies-demo.php">Add Cookies</a> | <a href="read-cookies-demo.php">Read Cookies</a> | <a href="delete-cookies-demo.php">Delete Cookies</a></nav>
<script>
function getCookie(cookieName) {
const prefix = `${cookieName}=`;
const parts = document.cookie.split(';');
for (const part of parts) {
const cookie = part.trim();
if (cookie.startsWith(prefix)) {
return decodeURIComponent(cookie.slice(prefix.length));
}
}
return null;
}
document.getElementById('all-cookies').textContent = `Cookies: ${document.cookie || '(none)'}`;
const name = getCookie('name');
document.getElementById('welcome').textContent = name ? `Welcome ${name}` : 'The name cookie is not available.';
</script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Delete a JavaScript cookie</title>
</head>
<body>
<button type="button" id="delete-cookie">Delete Cookie</button>
<p id="status" aria-live="polite"></p>
<nav><a href="add-cookies-demo.php">Add Cookies</a> | <a href="read-cookies-demo.php">Read Cookies</a> | <a href="delete-cookies-demo.php">Delete Cookies</a></nav>
<script>
document.getElementById('delete-cookie').addEventListener('click', () => {
document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/javascript_tutorial; SameSite=Lax';
document.getElementById('status').textContent = 'Cookie deleted.';
});
</script>
</body>
</html>
document.write() after a page has loaded can replace the document. The demos now update normal DOM elements instead.path does not remove the original cookie.HttpOnly.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.