JavaScript Cookie Update

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

What Is Updating a Cookie?

Updating a cookie means writing again with the same name, same path (and domain, if used). There is no separate updateCookie() API — every update is another document.cookie assignment that overwrites the matching entry.

Warning Lifetime on update

If you omit max-age / expires when updating, a persistent cookie becomes a session cookie. Re-send lifetime whenever you want it to stay.

Remember
// create
document.cookie = "theme=light; path=/; max-age=2592000"

// update (same name + path + lifetime attrs)
document.cookie = "theme=dark; path=/; max-age=2592000"

same name + path  → overwrite
different path    → duplicate cookie
no max-age/expires → becomes session
GoalPrefer
Change valueRewrite same name + path
Extend lifetimeRewrite with new max-age
Keep persistenceAlways re-send max-age/expires
Avoid duplicatesNever change path by accident

How to Update Cookies

Match the cookie identity, rewrite the value, and re-apply path and lifetime.

  1. Identify the cookie: same name, same path (usually /), same domain if set.
  2. Assign a new document.cookie string with the new value.
  3. Re-send max-age or expires if the cookie should stay persistent.
  4. Verify with document.cookie or DevTools — a wrong path creates a second cookie.
PieceRequired?Role
Same nameYesTargets the cookie to replace
Same pathYesCompletes the cookie identity
New valueUsualWhat you want stored after update
max-age / expiresIf persistentKeeps lifetime from becoming session

Pseudocode

Pseudocode
name, newValue = update target
path = original path            // usually "/"
seconds = original lifetime     // or new duration

cookie = name + "=" + encode(newValue)
cookie += "; path=" + path
if seconds is a number:
    cookie += "; max-age=" + seconds

document.cookie = cookie        // overwrite if identity matches

Cheat Sheet

Keep these update rules handy.

TopicDetail
APISame as write: document.cookie = …
Identityname + path (+ domain)
OverwriteMatching identity replaces the old value
MismatchDifferent path → duplicate cookie
Omit lifetimeBecomes a session cookie
Sliding sessionRewrite same value + fresh max-age
HttpOnlyNot updatable from JavaScript

Live Preview

Seed a theme cookie, then update its value while keeping path=/ and a 30-day max-age.

Uses path=/ and max-age=2592000 (30 days) on every write so updates overwrite instead of duplicating.

Result
Click “Seed theme=light”, then choose a value and “Update theme”.

document.cookie → (current jar)

JavaScript Examples

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

Example 1 — Update a Cookie Value

Change username from JohnDoe to JaneDoe with the same path and lifetime.

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

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

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

How It Works

  1. Create first. Store username=JohnDoe with path=/ and a 7-day max-age.
  2. Write again. Same name and path, new value JaneDoe.
  3. Browser overwrites. Matching identity replaces the old entry.
  4. Other cookies stay. Only the matching name/path pair changes.

Example 2 — Refresh max-age (Sliding Session)

Keep the same token but extend how long it survives idle time.

JavaScript
const oneHour = 60 * 60;

document.cookie =
  "session=token-abc; max-age=" + oneHour + "; path=/; SameSite=Lax";

function touchSession() {
  document.cookie =
    "session=token-abc; max-age=" + oneHour + "; path=/; SameSite=Lax";
  console.log("Session expiration refreshed");
}

touchSession();
Try It Yourself

How It Works

  1. Create a session cookie. Value stays token-abc; lifetime is one hour.
  2. Call on activity. touchSession() rewrites the same name and value.
  3. Countdown resets. Fresh max-age starts from “now.”
  4. Why it helps. Active users stay signed in; idle users expire after one hour.

Example 3 — Theme Preference Toggle

Update a UI preference cookie when the user chooses a mode.

JavaScript
const thirtyDays = 30 * 24 * 60 * 60;

document.cookie = "theme=light; max-age=" + thirtyDays + "; path=/";

function setTheme(mode) {
  document.cookie = "theme=" + mode + "; max-age=" + thirtyDays + "; path=/";
  console.log("Theme updated to:", mode);
}

setTheme("dark"); // theme=dark
Try It Yourself

How It Works

  1. Store a default. Initial write saves theme=light for 30 days.
  2. Toggle with a helper. setTheme("dark") rewrites the value.
  3. Keep path and lifetime. Same path=/ and max-age prevent session downgrade.
  4. Common pattern. Preferences like theme and language update this way.

Example 4 — Path Mismatch Creates a Duplicate

See why an “update” fails when path does not match the original cookie.

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

// Intended update — but path differs
document.cookie = "username=JaneDoe; max-age=604800; path=/account";

console.log(document.cookie);
// May show BOTH username cookies
Try It Yourself

How It Works

  1. Create at root. First cookie uses path=/.
  2. Write with another path. path=/account is a different identity.
  3. Two cookies exist. Name alone is not enough — path completes the key.
  4. Fix. Reuse the original path, or delete the old cookie first — see Cookie Path.

Edge Cases & Pitfalls

Check these before shipping cookie update logic.

trap

Update without lifetime

Omitting max-age/expires turns a persistent cookie into a session cookie.

path

Path mismatch duplicates

A different path creates a second cookie instead of overwriting. Match path every time.

HttpOnly

HttpOnly is server-only

Scripts cannot read or update HttpOnly cookies. Use Set-Cookie on the server.

encode

Encode values on rewrite

Spaces and punctuation still need encodeURIComponent when you update — same rules as write.

Browser Support

Updating cookies uses the same document.cookie setter available in every browser that supports cookies in JavaScript.

✓ Baseline · DOM

document.cookie (update)

Supported across Chrome, Firefox, Safari, Edge, and legacy IE. Overwrite rules (name + path + domain) are consistent; verify in DevTools when duplicates appear.

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. Treat every update as a full rewrite of value + path + lifetime attributes.

Performance Notes

OperationCostBest for
One update writeO(1) assignPreference / session refresh
Update on every keystrokeUnnecessary I/ODebounce or update on commit
Many large cookiesHeader bloatKeep values small; prefer localStorage for client-only data

Updates are cheap as assignments, but cookies ride on matching requests. Refresh max-age on meaningful activity, not on every tiny UI event.

Key Takeaways

  • Role: an update is a rewrite with the same name + path (+ domain).
  • Lifetime: re-send max-age/expires or you get a session cookie.
  • Path: mismatch creates duplicates — keep path=/ consistent.
  • Sliding sessions: rewrite the same value with a fresh max-age.

One line: update by rewriting with the same name and path — and always re-attach the lifetime you still want.

Frequently Asked Questions

Assign a new document.cookie string with the same cookie name and the same path (and domain, if you set one). The browser replaces the matching entry instead of creating a separate cookie.
Browsers identify cookies by name + domain + path. Writing username=Jane with path=/account does not update username=John at path=/ — you get two cookies that share a name but differ in scope.
It becomes a session cookie and is removed when the browser session ends, even if the old version was persistent. Always re-send lifetime attributes when you want persistence.
Yes. Write the same name and value again with a new max-age or expires. Many apps refresh session cookies on activity this way.
No. HttpOnly cookies are invisible to document.cookie. Only the server can change them through Set-Cookie response headers.
Yes. Both use document.cookie assignment. An update is a write where name/path/domain match an existing cookie, so the browser overwrites instead of adding a sibling.

Next: Cookie Write

Review the full write API — attributes, encoding, Secure, and SameSite — that every update also relies on.

Cookie Write 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.

9 people found this page helpful