JavaScript Cookies — Update

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

What You’ll Learn

Updating a cookie means overwriting an existing entry with a new value or new attributes. This tutorial shows how that works with document.cookie, why path and domain must match, and how to refresh expiration safely.

01

Overwrite rule

Same name + path

02

Change value

New name=value

03

Refresh lifetime

New max-age

04

Path trap

Mismatch = duplicate

05

UI toggles

Theme preferences

06

Helper

updateCookie()

Introduction

Cookies often need to change after they are first set—a user switches from light to dark theme, a cart ID gets refreshed, or a “remember me” session needs more time. JavaScript has no separate updateCookie() API on the browser; you update by writing again with matching scope attributes.

If you already know how to write (set) cookies, updating is the next step: same syntax, stricter rules about which existing cookie you are replacing.

What Does “Update” Mean for Cookies?

The browser stores each cookie as a tuple of name, domain, and path, plus value and flags. When a new assignment matches that tuple, the old entry is replaced. When it does not match—especially on path—you get a second cookie with the same name in a different scope.

You can update the value (e.g. theme=dark), the lifetime (max-age or expires), or security flags (Secure, SameSite) in one assignment.

💡
Beginner Tip

Think of updating as “save over” rather than “edit in place.” You send the full cookie string again; the browser decides whether to replace an existing row or add a new one based on name, domain, and path.

📝 Syntax

Minimum update—change the value, keep scope identical:

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

// Update — same name and path
document.cookie = "username=JaneDoe; max-age=604800; path=/";

Refresh only the expiration (value unchanged):

JavaScript
document.cookie = "session=abc; max-age=3600; path=/";

// Slide the window forward another hour
document.cookie = "session=abc; max-age=3600; path=/";

Steps to update safely

  1. Use the same cookie name as the one you want to replace.
  2. Repeat the same path (and domain if you set it).
  3. Include max-age or expires if the cookie should stay persistent.
  4. Encode values with encodeURIComponent when they contain special characters.

⚡ Quick Reference

GoalWhat to write
Change value onlySame name, path, max-age; new value
Extend sessionSame name, value, path; new max-age
Site-wide cookieAlways include path=/
Avoid duplicatesNever change path/domain mid-update
Verify changeRead with parse helper or DevTools
Server-only cookiesHttpOnly — update via server Set-Cookie

📋 Write vs Update

Both use document.cookie = .... The difference is whether the browser finds an existing cookie with the same name, domain, and path to replace.

First write
cartId=1

Creates new entry

Update
cartId=2

Same path → overwrite

Path trap
path=/shop

Different path → duplicate

Session trap
no max-age

Persistent → session

Cookie Expiration and Path When Updating

When you update, the browser applies whatever attributes you send in that assignment. Omitting max-age or expires turns a previously persistent cookie into a session cookie that disappears when the tab or browser closes.

JavaScript
// Extend lifetime — keep path=/
document.cookie = "username=JaneDoe; max-age=1209600; path=/";

// WRONG for a site-wide cookie — creates a second username at /account
document.cookie = "username=JaneDoe; max-age=1209600; path=/account";

For expiration details see Expires & max-age. For path rules see Path attribute.

Examples Gallery

Use DevTools → Application → Cookies to confirm overwrites, or open the Try-it labs. Each example assumes a cookie was set first, then updated.

📚 Getting Started

Replace a stored value while keeping scope stable.

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

Both assignments target the same cookie identity (username at path=/). The second line replaces the value; other cookies on the page are untouched.

📈 Practical Patterns

Sliding expiration, UI state, pitfalls, and helpers.

Example 2 — Refresh max-age (Sliding Session)

Keep the same session 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

Each call resets the countdown to one hour from “now.” Call touchSession() on user activity to implement a sliding session window without changing the token value.

Example 3 — Theme Preference Toggle

Update a UI preference cookie when the user clicks a button.

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

The initial write stores light. setTheme("dark") overwrites the value while preserving the 30-day lifetime and site-wide path—a common pattern for accessibility and display settings.

Example 4 — Path Mismatch Creates a Duplicate

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

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

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

console.log(document.cookie);
// May show BOTH: username=JohnDoe and username=JaneDoe
// (browser sends the most specific match per request)
Try It Yourself

How It Works

The browser treats these as two distinct cookies because their paths differ. Always reuse the original path (usually /) when updating, or delete the old cookie first before changing scope.

Example 5 — Reusable updateCookie Helper

Centralize encoding, path defaults, and lifetime refresh.

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

updateCookie("lang", "en-US", 604800);
updateCookie("lang", "fr-FR", 604800);

console.log(document.cookie); // lang=fr-FR
Try It Yourself

How It Works

The helper always writes with path=/, so updates hit the same cookie row every time. Pair it with a getCookie parser from the read cookies guide to build full read/update flows.

🚀 Common Use Cases

  • Theme / language switches — overwrite preference cookies on user choice.
  • Sliding sessions — refresh max-age on each authenticated action.
  • Cart quantity changes — update a lightweight cart summary cookie.
  • Consent upgrades — change consent=essential to consent=all.
  • A/B reassignment — rare, but sometimes buckets are updated after login.
  • Feature flag toggles — flip boolean-like values client-side before server sync.

🧠 How the Browser Applies an Update

1

Parse new string

Split the assignment into name, value, and attributes.

Input
2

Lookup existing

Search the cookie jar for the same name + domain + path.

Match
3

Replace or insert

Match found → overwrite value and flags. No match → add new entry.

Store
4

Future requests

Updated value and expiration ride along on the next eligible HTTP requests automatically.

📝 Notes & Common Pitfalls

  • Missing expiration — updating without max-age/expires downgrades persistent cookies to session cookies.
  • Path mismatch — the most common reason an “update” appears to do nothing or creates duplicates.
  • Size limits — values still capped at ~4 KB; oversized updates are rejected silently.
  • HttpOnly — auth cookies set by the server cannot be updated from script; use an API instead.
  • Encoding — if the original value was encoded, encode again on update for consistency.
  • Reading is ambiguousdocument.cookie may list multiple same-name cookies; parse carefully or inspect DevTools.

Browser Support

Updating cookies uses the same document.cookie API as writing them. It is supported in every JavaScript-enabled browser.

Baseline · DOM Level 0

document.cookie (update)

Universal in Chrome, Firefox, Safari, Edge, and Internet Explorer. SameSite and Secure attribute behavior follows modern standards in current browsers.

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: No polyfill needed for updates. Test path and expiration behavior in DevTools when debugging duplicate cookies or unexpected session expiry.

Conclusion

Updating cookies is rewriting with intent: same name, same scope, and the attributes you want to keep. Change values for user preferences, refresh max-age for sliding sessions, and always align path with the original cookie.

When updates get confusing, open DevTools and look for duplicate names with different paths—that is usually the root cause.

💡 Best Practices

✅ Do

  • Repeat path=/ on every update
  • Re-send max-age for persistent cookies
  • Use a shared helper for write and update
  • Verify in DevTools after changes
  • Encode values on every assignment

❌ Don’t

  • Change path when you mean to overwrite
  • Omit expiration on persistent cookies
  • Assume document.cookie shows one row per name
  • Store secrets in script-readable cookies
  • Expect to update HttpOnly server cookies

Key Takeaways

Knowledge Unlocked

Five things to remember when updating cookies

Overwrite safely without surprise duplicates.

5
Core concepts
🗺 02

Match path

Scope must align.

Scope
03

Re-send max-age

Keep persistence.

Lifetime
🔄 04

Sliding session

Refresh on activity.

Pattern
05

Duplicates

Path mismatch trap.

Pitfall

❓ Frequently Asked Questions

Assign a new document.cookie string with the same cookie name and the same path (and domain, if you set one originally). The browser replaces the matching entry instead of creating a separate cookie.
Browsers identify cookies by name + domain + path together. Writing username=Jane with path=/account does not update username=John stored at path=/ — you end up with two cookies that share a name but differ in scope.
The updated cookie 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 intend to keep the cookie after a restart.
Yes. Write the same name and value again with a new max-age or expires attribute. 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.
Technically yes — both use document.cookie assignment. An update is simply a write where the name/path/domain tuple matches an existing cookie, so the browser overwrites instead of adding a sibling entry.
Did you know?

There is no JavaScript method named updateCookie built into the browser. Every update is just another document.cookie assignment—the browser decides whether it is an overwrite based on name, domain, and path.

Continue to Write Cookies

Learn how to create cookies for the first time with path, lifetime, and security attributes.

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.

6 people found this page helpful