JavaScript Cookies — Write (Set)

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Client storage

What You’ll Learn

Cookies let the browser remember small pieces of data between page loads. This tutorial shows how to write (create or set) cookies from JavaScript using document.cookie, including attributes that control lifetime, scope, and security.

01

Basic syntax

name=value

02

Session vs persistent

max-age / expires

03

Path scope

path=/

04

Security flags

Secure, SameSite

05

Encoding

encodeURIComponent

06

Helper pattern

Reusable setCookie()

Introduction

Cookies are small name–value strings the browser stores and sends back to the server on matching requests. They are useful for remembering UI preferences (theme, language), shopping-cart hints, or lightweight session markers—when used carefully.

In client-side JavaScript, you write cookies by assigning to document.cookie. Each assignment touches one cookie; it does not replace every cookie already stored for the site.

What Are Cookies?

A cookie is a key–value pair plus optional attributes (expiration, path, domain, security flags). The browser attaches eligible cookies to HTTP requests for the same origin, so both JavaScript and server code can cooperate on session state.

Cookies are limited to about 4 KB each and roughly 50 cookies per domain in most browsers—fine for tokens and preferences, not for large payloads. For bigger client data, consider localStorage or server-side storage.

💡
Beginner Tip

Think of document.cookie as a special notepad: reading it shows every cookie JavaScript can see; writing appends or updates a single line. Server-only HttpOnly cookies never appear in that notepad.

📝 Syntax

Minimum form to create a cookie from JavaScript:

JavaScript
document.cookie = "username=JohnDoe";

Full form with common attributes (all separated by semicolons):

JavaScript
document.cookie = "username=JohnDoe; max-age=604800; path=/; Secure; SameSite=Lax";

Writable attributes (from JavaScript)

  • name=value — required pair that identifies the cookie.
  • expires — UTC date string (e.g. from Date.toUTCString()).
  • max-age — lifetime in seconds; often easier than expires.
  • path — URL prefix where the cookie is sent (default is current path).
  • domain — host scope (use carefully; cannot set for unrelated domains).
  • Secure — cookie is sent only over HTTPS.
  • SameSiteStrict, Lax, or None (with Secure).

Not settable from JavaScript

  • HttpOnly — must be set by the server; blocks script access (good for auth tokens).

⚡ Quick Reference

GoalCode snippet
Session cookie (until tab closes)document.cookie = "key=value"
Persist 7 days...; max-age=604800; path=/
Site-wide accessAlways add path=/
HTTPS onlyAppend Secure
CSRF-friendly defaultSameSite=Lax
Safe special charactersencodeURIComponent(value)

📋 Session vs Persistent Cookies

When you omit expiration attributes, the browser treats the cookie as a session cookie. Add max-age or expires to keep it after the browser restarts.

Session
theme=light

Gone when session ends

7-day persistent
max-age=604800

604800 seconds = 7 days

Path trap
no path set

Defaults to current folder

Fix
path=/

Visible on whole site

Setting Cookies for Specific Paths vs the Whole Site

The path attribute controls which URLs on your domain include the cookie. A cookie with path=/shop is sent to /shop, /shop/cart, and other URLs under that prefix—not to unrelated pages like /blog.

JavaScript
// Only URLs starting with /about receive this cookie
document.cookie = "tour=step2; path=/about";

// Every page on the site can read this cookie
document.cookie = "user=JohnDoe; path=/";

If you skip path, the browser defaults to the directory of the current page. That is a common reason a cookie “works here but not on the homepage.” For site-wide cookies, always set path=/.

Examples Gallery

Open DevTools → Application → Cookies to inspect results, or use the Try-it links. Each example builds on the last.

📚 Getting Started

Create your first cookie with the simplest assignment.

Example 1 — Write a Session Cookie

Set a cookie with only a name and value. It lasts until the browser session ends.

JavaScript
document.cookie = "username=JohnDoe";

// Reading shows this cookie among others (name=value pairs joined by "; ")
console.log(document.cookie);
Try It Yourself

How It Works

The browser stores username=JohnDoe for the current origin. Without path=/, scope defaults to the current URL path—fine for demos, but production code usually adds path=/.

📈 Practical Patterns

Lifetime, scope, security, and reusable helpers.

Example 2 — Persistent Cookie with max-age

Keep a cookie for seven days using seconds instead of a manual date string.

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

document.cookie = "prefs=compact; max-age=" + sevenDays + "; path=/";

console.log("Cookie set for 7 days");
Try It Yourself

How It Works

max-age=604800 tells the browser to delete the cookie 604800 seconds (7 days) after it was set. Prefer max-age over expires when you think in relative durations.

Example 3 — Site-Wide Cookie with path=/

Ensure every page on your domain can access the cookie.

JavaScript
document.cookie = "cartId=abc123; path=/; max-age=86400";

// cartId is sent on /, /shop, /checkout, etc.
Try It Yourself

How It Works

path=/ is the root of the site. Combined with max-age=86400 (one day), the cart identifier survives navigation and a browser restart within that day.

Example 4 — Secure and SameSite=Lax

Add modern security attributes when serving pages over HTTPS.

JavaScript
document.cookie = [
  "session=abc",
  "max-age=3600",
  "path=/",
  "Secure",
  "SameSite=Lax"
].join("; ");

// Secure cookies are ignored on plain http:// pages
Try It Yourself

How It Works

Secure limits transmission to HTTPS. SameSite=Lax is a sensible default that still allows normal top-level navigation while reducing cross-site request risks. Use SameSite=None; Secure only when you intentionally need third-party cookie behavior.

Example 5 — Reusable setCookie Helper

Encode values safely and centralize attribute defaults.

JavaScript
function setCookie(name, value, maxAgeSeconds) {
  const encoded = encodeURIComponent(value);
  let cookie = name + "=" + encoded + "; path=/; SameSite=Lax";
  if (typeof maxAgeSeconds === "number") {
    cookie += "; max-age=" + maxAgeSeconds;
  }
  if (location.protocol === "https:") {
    cookie += "; Secure";
  }
  document.cookie = cookie;
}

setCookie("greeting", "Hello, world!", 604800);
console.log(document.cookie);
Try It Yourself

How It Works

encodeURIComponent turns commas and spaces into safe escape sequences. The helper always sets path=/ and SameSite=Lax, adds Secure on HTTPS, and optionally applies max-age. Pair it with a matching getCookie that uses decodeURIComponent when you read values back.

🚀 Common Use Cases

  • UI preferences — theme, font size, or sidebar state (theme=dark).
  • Consent banners — remember that the user accepted analytics (consent=1).
  • Localization — store chosen language code for the next visit.
  • Anonymous cart IDs — short-lived identifiers before login.
  • A/B test buckets — sticky assignment to variant A or B.
  • Feature flags — lightweight toggles shared with server routes.

🧠 What Happens When You Write a Cookie

1

Parse assignment

The browser splits your string on semicolons into name=value plus attributes.

Input
2

Validate scope

Domain, path, size, and security flags must pass browser rules or the cookie is rejected.

Policy
3

Store or update

Matching name + domain + path updates the value; otherwise a new cookie entry is created.

Jar
4

Attach to requests

On later navigations and fetches, eligible cookies ride along in the Cookie header automatically.

Updating a Cookie While Writing

To change a value, write the same cookie name again. Include the same path (and domain if you used one) or the browser may create a second cookie with overlapping names.

JavaScript
document.cookie = "username=JohnDoe; max-age=604800; path=/";
document.cookie = "username=JaneDoe; max-age=604800; path=/";

// Only one username cookie remains for path=/

See also: Update cookies for focused coverage of expiration and attribute changes.

📝 Notes & Common Pitfalls

  • Assigning document.cookie never clears unrelated cookies—only matches on name/path/domain update.
  • Without path=/, cookies set on /js/cookies/write may not appear on /.
  • Values with ; or = break parsing unless encoded.
  • Each cookie is capped at ~4 KB; browsers drop oversized cookies silently.
  • Never store passwords or raw JWTs in JavaScript-readable cookies when avoidable.
  • HttpOnly cookies must be issued by the server—scripts cannot create them.

Browser Support

document.cookie has been available since the earliest JavaScript-enabled browsers. Modern attributes like SameSite are supported in all current evergreen browsers.

Baseline · DOM Level 0

document.cookie (write)

Universal in Chrome, Firefox, Safari, Edge, and Internet Explorer. SameSite=Lax/Strict/None behavior is standardized in modern browsers; test third-party flows explicitly.

99% Universal 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 Excellent

Bottom line: Safe to use everywhere for basic cookie writes. Always feature-detect HTTPS before adding Secure, and remember that embedded third-party iframes may block cookies under browser privacy settings.

Conclusion

Writing cookies in JavaScript boils down to formatted strings assigned to document.cookie. Start with name=value, then layer path=/, lifetime attributes, and security flags as your app needs them.

Use a small helper to encode values and keep defaults consistent. For sensitive session tokens, prefer server-set HttpOnly cookies instead of client-only writes.

💡 Best Practices

✅ Do

  • Set path=/ for site-wide cookies
  • Use max-age for relative lifetimes
  • Encode values with encodeURIComponent
  • Add Secure on HTTPS sites
  • Default to SameSite=Lax

❌ Don’t

  • Store secrets in non-HttpOnly cookies
  • Assume writing replaces all cookies
  • Omit path on deep URLs
  • Put large JSON blobs in cookies
  • Expect Secure cookies on http://

Key Takeaways

Knowledge Unlocked

Five things to remember when writing cookies

Your foundation for safe client-side cookie creation.

5
Core concepts
02

max-age

Persist beyond session.

Lifetime
🗺 03

path=/

Site-wide scope.

Scope
🔒 04

Secure

HTTPS only.

Safety
🔤 05

Encode

Special chars safe.

Parsing

❓ Frequently Asked Questions

Assign a name=value string to document.cookie. Each assignment creates or updates one cookie. Example: document.cookie = "theme=dark; path=/; max-age=604800".
No. Writing one cookie does not remove existing cookies with different names. To update a cookie, write the same name again with a new value (and matching path/domain if you set them originally).
A session cookie has no expires or max-age attribute and is removed when the browser session ends. A persistent cookie includes expires or max-age and survives browser restarts until it expires or is deleted.
No. HttpOnly cookies can only be created by the server through Set-Cookie response headers. JavaScript cannot read or write HttpOnly cookies, which helps protect session tokens from XSS scripts.
Cookie values cannot safely contain semicolons, spaces, or non-ASCII characters without encoding. encodeURIComponent(value) prevents broken cookies and parsing errors.
path=/ makes the cookie available to every page on the current origin (same scheme, host, and port). A narrower path like path=/shop limits visibility to URLs under /shop.
Did you know?

Reading document.cookie returns a single string like "a=1; b=2", but writing only accepts one cookie per assignment. That asymmetry trips up many beginners the first time they try to “replace all cookies” with one line.

Continue to File Handling

After cookies, learn how JavaScript reads and processes files from user input.

File Handling 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.

6 people found this page helpful