JavaScript Cookie Write

Beginner
8 min read
Updated: Oct 2026
4 examples
Live preview

What Is Writing a Cookie?

Writing a cookie means assigning a name=value string to document.cookie. Each assignment creates or updates one cookie. Optional attributes like path, max-age, Secure, and SameSite follow after semicolons.

Note HttpOnly is server-only

JavaScript cannot set or read HttpOnly cookies. Those come only from server Set-Cookie headers — use them for session tokens.

Remember
document.cookie = "name=value; path=/; max-age=SECONDS; SameSite=Lax"

one assignment → one cookie
omit max-age/expires → session cookie
encodeURIComponent(value) → safe characters
Secure → HTTPS only
GoalPrefer
Site-wide cookiepath=/
Last 7 daysmax-age=604800
Safe valuesencodeURIComponent(value)
Modern defaultsSameSite=Lax (+ Secure on HTTPS)

How to Write Cookies

Build a name=value string, add path and lifetime, encode the value, then assign once.

  1. Choose a name and value; encode the value with encodeURIComponent.
  2. Add path=/ unless you intentionally want a narrower scope.
  3. Add max-age (seconds) for persistence, or omit it for a session cookie.
  4. Add SameSite=Lax (and Secure on HTTPS) for safer defaults.
PieceRequired?Role
name=valueYesCookie identity and payload
pathRecommendedURL scope — prefer /
max-age / expiresOptionalPersistence vs session
SameSite / SecureRecommendedCross-site and HTTPS safety

Pseudocode

Pseudocode
name, value = cookie data
seconds = lifetime in seconds   // or null for session

cookie = name + "=" + encodeURIComponent(value)
cookie += "; path=/"
cookie += "; SameSite=Lax"

if seconds is a number:
    cookie += "; max-age=" + seconds

if page is HTTPS:
    cookie += "; Secure"

document.cookie = cookie        // one cookie per assignment

Cheat Sheet

Keep these write-side facts handy.

TopicDetail
APIdocument.cookie = "…"
One writeCreates or updates one cookie
SessionOmit max-age and expires
7 daysmax-age=604800
Site-widepath=/
EncodingencodeURIComponent(value)
HttpOnlyServer Set-Cookie only
ReadbackAttributes are not in document.cookie

Live Preview

Build a cookie assignment and apply it in this browser. Inspect the result in document.cookie.

Demo cookies use path=/. On plain HTTP, a Secure flag is skipped so the demo still works locally.

Result
mode = session
assignment =
  document.cookie = "ctfUser=JohnDoe; path=/; SameSite=Lax"

document.cookie → (current jar)

JavaScript Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Write a Session Cookie with path=/

Set a cookie with a name and value. No lifetime means session scope.

JavaScript
document.cookie = "username=JohnDoe; path=/; SameSite=Lax";

console.log(document.cookie);
// "username=JohnDoe" (plus any other visible cookies)
Try It Yourself

How It Works

  1. Assign once. document.cookie = … writes one cookie.
  2. Add path=/. The cookie is available on every page of this origin.
  3. Skip lifetime. No max-age/expires → session cookie.
  4. Read back names only. Attributes never appear in the getter string.

Example 2 — Persistent Cookie with max-age

Keep a cookie for seven days using relative seconds.

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

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

console.log(document.cookie);
Try It Yourself

How It Works

  1. Think in seconds. Seven days = 604800.
  2. Write with max-age. The browser deletes the cookie after that many seconds.
  3. Keep path=/. Preferences stay visible across the site.
  4. Prefer max-age. Simpler than building UTC expires strings — see Cookie Expires.

Example 3 — Encode Values Safely

Spaces and punctuation need encoding before they go into a cookie.

JavaScript
const text = "Hello, world!";

document.cookie =
  "greeting=" + encodeURIComponent(text) +
  "; path=/; max-age=604800; SameSite=Lax";

console.log(document.cookie);
// greeting=Hello%2C%20world!
Try It Yourself

How It Works

  1. Start with plain text. Commas and spaces are unsafe raw cookie characters.
  2. Encode before write. encodeURIComponent turns them into percent escapes.
  3. Store the encoded value. The browser keeps the safe string.
  4. Decode on read. Use decodeURIComponent in your reader — see Cookie Read.

Example 4 — Secure and SameSite=Lax

Add modern security attributes for HTTPS pages.

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

if (location.protocol === "https:") {
  cookie += "; Secure";
}

document.cookie = cookie;
console.log(document.cookie);
Try It Yourself

How It Works

  1. Build attributes. Join name, lifetime, path, and SameSite with "; ".
  2. SameSite=Lax. A solid default for same-site use and normal top-level navigation.
  3. Add Secure on HTTPS. Without HTTPS, browsers ignore Secure cookies.
  4. Use None carefully. SameSite=None also requires Secure and is for intentional cross-site cases.

Edge Cases & Pitfalls

Check these before shipping cookie writes.

path

Forgetting path=/

Default path is the current page directory. Cookies then “vanish” on other routes — see Cookie Path.

encode

Raw spaces / semicolons

Unencoded values can truncate or break the cookie string. Always encode user text.

Secure

Secure on HTTP fails silently

On http://, browsers refuse Secure cookies. Feature-detect protocol or skip the flag in local demos.

HttpOnly

Cannot set HttpOnly from JS

Auth tokens should be set by the server with HttpOnly. Client-readable cookies are for non-secret preferences.

Browser Support

Writing cookies via document.cookie is a long-standing DOM feature. max-age, path, Secure, and SameSite are supported in all modern browsers.

✓ Baseline · DOM

document.cookie (write)

Supported across Chrome, Firefox, Safari, Edge, and legacy IE. Prefer max-age + path=/ + SameSite=Lax for new code; add Secure on HTTPS.

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 for production. Keep values small, encode carefully, and never store secrets in script-readable cookies.

Performance Notes

ChoiceEffectBest for
One writeO(1) assignPreferences, short flags
path=/ cookiesSent on every requestSmall, needed-everywhere values
Many / large cookiesHeader bloatAvoid — use localStorage for client-only data

Writes themselves are cheap. The cost is bytes on later requests. Prefer short lifetimes and tiny values. For modern async APIs, see the Cookie Store API.

Key Takeaways

  • Role: assign document.cookie once per cookie to create or update it.
  • Defaults: use path=/, max-age when persistent, and SameSite=Lax.
  • Encode: wrap values with encodeURIComponent.
  • Secrets: keep auth tokens HttpOnly on the server — not in JS-writable cookies.

One line: write with name=value; path=/; max-age=…; SameSite=Lax, encode values, and never store secrets in script-readable cookies.

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, write the same name again with a matching path/domain.
A session cookie has no expires or max-age and is normally removed when the browser session ends. A persistent cookie includes expires or max-age and can survive restarts until it expires or is deleted.
No. HttpOnly cookies can only be created by the server through Set-Cookie headers. JavaScript cannot read or write HttpOnly cookies.
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. A narrower path like path=/shop limits visibility to URLs under /shop.

Next: File Handling

Continue with JavaScript file handling — reading and working with files in the browser.

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.

11 people found this page helpful