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()
Fundamentals
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.
Concept
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.
Foundation
📝 Syntax
Minimum form to create a cookie from JavaScript:
JavaScript
document.cookie = "username=JohnDoe";
Full form with common attributes (all separated by semicolons):
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.
SameSite — Strict, Lax, or None (with Secure).
Not settable from JavaScript
HttpOnly — must be set by the server; blocks script access (good for auth tokens).
Cheat Sheet
⚡ Quick Reference
Goal
Code snippet
Session cookie (until tab closes)
document.cookie = "key=value"
Persist 7 days
...; max-age=604800; path=/
Site-wide access
Always add path=/
HTTPS only
Append Secure
CSRF-friendly default
SameSite=Lax
Safe special characters
encodeURIComponent(value)
Compare
📋 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
Scope
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=/.
Hands-On
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);
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.
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.
On HTTPS: cookie stored with Secure + SameSite=Lax
On HTTP: Secure flag prevents storage
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.
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.
Applications
🚀 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.
Update
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.
Important
📝 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.
Compatibility
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 ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
document.cookieExcellent
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.
Wrap Up
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.
Your foundation for safe client-side cookie creation.
5
Core concepts
📝01
One at a time
Each assignment sets one cookie.
API
⏳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.