JavaScript Cookies

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 5 Tutorials
document.cookie

What You’ll Learn

Cookies let web apps remember preferences, sessions, and lightweight state between page loads. This hub covers 5 focused tutorials on writing, reading, updating, path scope, and expiration — plus security basics every beginner should know.

01

Write

document.cookie

02

Read

getCookie()

03

Update

Overwrite

04

path

URL scope

05

max-age

Lifetime

06

5 guides

Full index

Introduction

Cookies are small text files the browser stores and attaches to HTTP requests for your site. They are ideal for session IDs, theme preferences, and “remember me” flags—not for large data (see localStorage for bigger client storage).

What Are Cookies?

Each cookie is a name=value pair plus optional attributes (path, max-age, Secure, SameSite). JavaScript reads and writes cookies through the document.cookie API. The server can also set cookies via the Set-Cookie response header.

💡
Beginner Tip

document.cookie returns all visible cookies as one semicolon-separated string. Setting a cookie only changes one name at a time—it does not replace every cookie on the page.

Key Features

  • Small size — about 4 KB per cookie; keep values short.
  • Expiration — session cookies die with the tab; persistent cookies use max-age or expires.
  • Scopepath and domain limit where the browser sends the cookie.
  • Automatic sending — matching cookies ride along on every request to your server (unlike localStorage).

Storage Limitations

  • ~4 KB per cookie value (rough limit; browsers may vary slightly).
  • ~20–50 cookies per domain (browser-dependent).
  • Same-origin rules — scripts on other domains cannot read your cookies.

📝 Syntax

Set a basic cookie:

JavaScript
document.cookie = "username=Ada";

// Persistent cookie — 7 days, site-wide path
document.cookie = "theme=dark; path=/; max-age=604800";

Common attributes

AttributeExamplePurpose
pathpath=/Which URLs include the cookie
max-agemax-age=3600Seconds until expiry
expiresexpires=Thu, 01 Jan 2026…UTC expiry date
SecureSecureHTTPS only
SameSiteSameSite=LaxCross-site send policy

⚡ Quick Reference

GoalApproach
Set a cookiedocument.cookie = "k=v; path=/"
Read all cookiesdocument.cookie (string)
Delete a cookiename=; path=/; max-age=0
Encode special charsencodeURIComponent(value)
Session cookieOmit expires and max-age

Cookie Security Considerations

  • HttpOnly — set only by the server; JavaScript cannot read these cookies (good for session tokens).
  • Secure — cookie sent only over HTTPS; add in production sites.
  • SameSiteStrict, Lax, or None controls cross-site requests (CSRF mitigation).
  • No secrets in JS-readable cookies — anything in document.cookie is visible to scripts on the page.
  • Prefer short lifetimes — especially for authentication-related values.

👀 document.cookie String

What you might see when reading cookies on a page:

Cookie Tutorial Index

Search by topic or browse by category. Each guide includes syntax, five try-it examples, and FAQs.

Cookie Operations

3 tutorials

Create, read, and change cookie values in the browser.

TopicDescriptionTutorial
Write (set) cookiesCreate cookies with document.cookie — name, value, path, max-age, Secure, and SameSite.Open
Read cookiesParse document.cookie, build getCookie helpers, and decode URI-encoded values.Open
Update cookiesOverwrite values and refresh expiration without creating duplicate cookies.Open

Attributes & Lifetime

2 tutorials

Scope cookies to paths and control when they expire.

TopicDescriptionTutorial
Path attributeControl which URL paths send a cookie — site-wide path=/ vs restricted prefixes.Open
Expires & max-ageSession vs persistent cookies, UTC expires dates, and delete with max-age=0.Open

Examples Gallery

Run these in the browser console or embed in a page. Check Application → Cookies in DevTools to verify results.

Example 1 — Set a Simple Cookie

Assign a name=value pair to create or update one cookie.

JavaScript
document.cookie = "username=Ada";
console.log(document.cookie);
Write tutorial

How It Works

Without path, the default path is the current URL directory. For site-wide cookies, always add path=/.

Example 2 — Read a Cookie by Name

Parse the cookie string to extract one value.

JavaScript
function getCookie(name) {
  const prefix = name + "=";
  const parts = decodeURIComponent(document.cookie).split(";");

  for (const part of parts) {
    const trimmed = part.trim();
    if (trimmed.startsWith(prefix)) {
      return trimmed.slice(prefix.length);
    }
  }
  return "";
}

console.log(getCookie("username"));
Read tutorial

How It Works

decodeURIComponent reverses encoding applied when the cookie was set. Split on ; because that separates cookie pairs in the string.

Example 3 — Delete a Cookie

Expire the cookie immediately with max-age=0 and the same path.

JavaScript
function deleteCookie(name) {
  document.cookie = name + "=; path=/; max-age=0";
}

deleteCookie("username");
console.log(getCookie("username"));
Expires tutorial

How It Works

If deletion fails, the path or domain probably does not match the original cookie. Inspect cookies in DevTools to compare attributes.

Example 4 — Persistent Cookie with max-age

Keep a theme preference for seven days (604800 seconds).

JavaScript
const oneWeek = 7 * 24 * 60 * 60;

document.cookie =
  "theme=dark; path=/; max-age=" + oneWeek + "; SameSite=Lax";
Expires tutorial

How It Works

max-age is relative (seconds from now). expires uses an absolute UTC date—both work; many developers prefer max-age for arithmetic.

Example 5 — Complete set / get / delete Helpers

Reusable functions for everyday cookie tasks (from the classic pattern).

JavaScript
function setCookie(name, value, days) {
  const maxAge = days * 24 * 60 * 60;
  document.cookie =
    encodeURIComponent(name) + "=" + encodeURIComponent(value) +
    "; path=/; max-age=" + maxAge + "; SameSite=Lax";
}

function getCookie(name) {
  const key = encodeURIComponent(name) + "=";
  const pairs = decodeURIComponent(document.cookie).split(";");
  for (const pair of pairs) {
    const trimmed = pair.trim();
    if (trimmed.startsWith(key)) {
      return trimmed.slice(key.length);
    }
  }
  return "";
}

function deleteCookie(name) {
  document.cookie =
    encodeURIComponent(name) + "=; path=/; max-age=0";
}

setCookie("username", "Ada", 365);
console.log(getCookie("username"));
deleteCookie("username");
Write tutorial

How It Works

Encoding names and values avoids breaking the cookie string when data contains =, ;, or spaces. Always use path=/ unless you intentionally scope to a subdirectory.

💬 Usage Tips

  • Always set path=/ for site-wide preferences unless you need a subdirectory scope.
  • Encode values with encodeURIComponent when they contain special characters.
  • Inspect in DevTools — Application tab → Cookies shows every attribute.
  • Match attributes on delete — same path and domain as when created.
  • Search this index — jump to any of 5 focused tutorials above.

⚠️ Common Pitfalls

  • Duplicate cookies — different path values create two cookies with the same name.
  • Storing passwords — never put credentials or JWTs in JS-readable cookies.
  • Assuming HttpOnly from JS — only the server can set HttpOnly via Set-Cookie.
  • Large payloads — cookies are not for big JSON blobs; use localStorage or the server.
  • Third-party context — modern browsers restrict cross-site cookies; plan for SameSite rules.

🧠 How Browser Cookies Work

1

Set cookie

JavaScript assigns document.cookie or the server sends Set-Cookie.

Create
2

Browser stores it

The cookie jar keeps name, value, path, domain, expiry, and flags.

Store
3

Sent on requests

Matching cookies attach to HTTP requests automatically via the Cookie header.

Send
=

Stateful browsing

Sessions and preferences persist across page loads without URL parameters.

Browser Support

document.cookie is supported in every browser and Node.js (with a document shim in tests). Attribute support for SameSite and Secure follows modern browser rules — always test in current Chrome, Firefox, and Safari.

Baseline · Universal

document.cookie API

Supported in Chrome, Firefox, Safari, Edge, IE 6+, Opera, and all modern Node.js test environments. Privacy settings and third-party blocking may limit cross-site cookies regardless of API support.

100% Core API
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
document.cookie Universal

Bottom line: Safe to use for client-readable cookies everywhere. HttpOnly cookies are server-set only; SameSite and Secure attributes require modern browsers for full behavior.

🎉 Conclusion

JavaScript cookies are a simple way to persist small pieces of state on the client. Master document.cookie, path scope, and expiration first, then explore the 5 focused tutorials for deeper patterns.

Handle cookies carefully: encode values, avoid secrets, and use server-set HttpOnly cookies for session tokens whenever possible.

💡 Best Practices

✅ Do

  • Use path=/ for site-wide cookies
  • Encode values with encodeURIComponent
  • Set short max-age for sensitive data
  • Use Secure on HTTPS sites
  • Prefer server HttpOnly for auth tokens

❌ Don’t

  • Store passwords or API keys in cookies
  • Assume delete works without matching path
  • Exceed ~4 KB per cookie
  • Rely on cookies for large datasets
  • Ignore SameSite and third-party rules

Key Takeaways

Knowledge Unlocked

Five things to remember about cookies

Your gateway to 5 cookie tutorials.

5
Core concepts
doc 02

document.cookie

JS API

Access
/ 03

path=/

Site scope

Scope
0 04

max-age=0

Delete

Remove
5 05

Index

Deep dives

Ref

❓ Frequently Asked Questions

Cookies are small text key=value pairs the browser stores and sends back to the server on matching requests. In JavaScript you access them through document.cookie — a string containing all cookies for the current page's URL scope.
Assign to document.cookie: document.cookie = "name=value; path=/; max-age=604800". Each assignment sets or updates one cookie. Add path, max-age, Secure, or SameSite as needed.
No. HttpOnly cookies are set by the server and hidden from document.cookie. That is intentional — it reduces XSS token theft. Only non-HttpOnly cookies are visible to scripts.
Overwrite it with an empty value and a past expiration: document.cookie = "name=; path=/; max-age=0". The path (and domain if used) must match how the cookie was originally set.
expires is an HTTP-date string in UTC. max-age is lifetime in seconds from now. Prefer max-age for simpler math. Omit both for a session cookie removed when the browser closes.
Read the overview, try the five examples, then open Write cookies from Cookie Operations. Use the search box to jump to any of the five topic tutorials.
Did you know?

Setting document.cookie never removes other cookies — it only creates or updates the cookie whose name you specify. To wipe everything, you must delete each name individually or use DevTools.

Start with Write Cookies

Learn how to set cookies with path, max-age, Secure, and SameSite in the first hands-on tutorial.

Write cookies tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful