JavaScript Cookie Expires

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

What Are expires and max-age?

Cookie lifetime attributes tell the browser how long to keep a cookie. Omit both for a session cookie; set expires (UTC date) or max-age (seconds) for a persistent cookie. Prefer max-age for new code.

Warning Session restore

Many browsers restore tabs on restart and can keep session cookies alive — do not rely on “session” expiry for security-sensitive data.

Remember
document.cookie = "name=value; path=/; max-age=SECONDS"
document.cookie = "name=value; path=/; expires=" + date.toUTCString()

no expires / max-age  → session cookie
max-age=0             → delete (same path)
both set              → max-age wins
GoalPrefer
Relative lifetimemax-age=604800 (7 days)
Absolute deadlineexpires= + toUTCString()
Temporary UI flagOmit both (session cookie)
Remove a cookiemax-age=0 + matching path

How to Use Cookie Lifetime

Pick a lifetime style, write one cookie assignment, and re-send lifetime on every update.

  1. Decide session (omit lifetime) vs persistent (max-age or expires).
  2. Prefer max-age in seconds — avoid timezone mistakes with date strings.
  3. Always include the same path (usually path=/) when setting or deleting.
  4. On update, re-send max-age/expires or the cookie becomes a session cookie.
PieceRequired?Role
name=valueYesCookie identity and payload
max-age or expiresOptionalPersistence; omit for session
pathRecommendedMust match when deleting/updating
SameSite / SecureRecommendedCross-site and HTTPS safety

Pseudocode

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

cookie = name + "=" + encode(value) + "; path=/"

if seconds is a number:
    if seconds <= 0:
        cookie += "; max-age=0"     // delete
    else:
        cookie += "; max-age=" + seconds

document.cookie = cookie           // one cookie per assignment

Cheat Sheet

Keep these lifetime facts handy while writing cookies.

TopicDetail
SessionOmit expires and max-age
1 hourmax-age=3600
1 daymax-age=86400
7 daysmax-age=604800
30 daysmax-age=2592000
Deletemax-age=0 (or past expires)
PrecedenceIf both set, max-age wins
Read expiry in JSNot available — use DevTools

Live Preview

Pick a lifetime mode. The demo builds a document.cookie assignment and can apply it in this browser.

Result
mode = session
assignment =
  document.cookie = "ctfDemo=ok; path=/; SameSite=Lax"

/* no expires / max-age → session cookie */
document.cookie → (current jar)

JavaScript Examples

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

Example 1 — Persistent Cookie with expires

Build a UTC expiry date with Date and toUTCString().

JavaScript
const date = new Date();
date.setTime(date.getTime() + 7 * 24 * 60 * 60 * 1000);

document.cookie =
  "username=" + encodeURIComponent("JohnDoe") +
  "; expires=" + date.toUTCString() +
  "; path=/; SameSite=Lax";

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

How It Works

  1. Start from now. Create a Date for the current instant.
  2. Add seven days. Milliseconds = days × 24 × 60 × 60 × 1000.
  3. Format as UTC. toUTCString() produces a valid expires HTTP-date.
  4. Write once. Assign to document.cookie with path=/ so the cookie is site-wide.

Example 2 — Prefer max-age (Relative Seconds)

Set a 7-day cookie without building a date string.

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

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

// Sliding refresh — rewrite to restart the countdown
document.cookie =
  "prefs=compact; max-age=" + sevenDays + "; path=/; SameSite=Lax";

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

How It Works

  1. Think in seconds. max-age counts from the moment the cookie is written.
  2. Write the cookie. 604800 means “keep for 7 days.”
  3. Refresh if needed. Writing again with the same max-age restarts the timer (sliding expiration).
  4. Why prefer it. No UTC string formatting — and if both attributes appear, max-age wins.

Example 3 — Session Cookie (No Lifetime)

Temporary flag cleared when the browser session ends (with restore caveats).

JavaScript
document.cookie = "flashBanner=dismissed; path=/; SameSite=Lax";

// No max-age or expires → session cookie
console.log(document.cookie);
Try It Yourself

How It Works

  1. Omit lifetime attrs. Neither expires nor max-age is set.
  2. Browser marks it session. It is usually removed when the session ends.
  3. Use for short UI state. One-time banners or wizard steps fit this pattern.
  4. Know the limit. Session restore can keep it — not a security boundary.

Example 4 — Delete with max-age=0

Overwrite the cookie with zero lifetime and the same path.

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

function deleteCookie(name) {
  document.cookie = name + "=; path=/; max-age=0";
}

deleteCookie("username");
console.log(document.cookie); // username gone
Try It Yourself

How It Works

  1. Create first. A persistent username cookie is written with max-age.
  2. Delete is a write. There is no separate delete API — overwrite with empty value.
  3. Zero lifetime. max-age=0 (or a past expires) removes it immediately.
  4. Match path. path=/ must match the original or the old cookie stays.

Edge Cases & Pitfalls

Check these before shipping cookie lifetime logic.

trap

Update without lifetime

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

path

Delete path must match

max-age=0 only removes the cookie if path (and domain if used) match the original write.

hidden

Expiry is not in reads

document.cookie returns name=value only. Use DevTools for Expires / Max-Age columns.

session

Session restore survives “close”

Browsers that restore tabs can keep session cookies. For sensitive data, use short max-age and server-side invalidation.

Browser Support

expires and max-age are standard cookie attributes available wherever document.cookie works. Prefer max-age for new JavaScript; expires remains useful for absolute deadlines.

✓ Baseline · HTTP cookies

Cookie Expires

Supported across Chrome, Firefox, Safari, Edge, and legacy IE. Both attributes are part of the long-standing cookie model used by document.cookie.

99% Universal attributes
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
expires / max-age Excellent

Bottom line: Safe for production. Prefer max-age for relative lifetimes; verify persistence and deletion in DevTools when behavior looks wrong.

Performance Notes

OperationCostBest for
Write one cookieO(1) assignSetting / refreshing lifetime
Read document.cookieSync string buildOccasional reads — avoid hot loops
Many long-lived cookiesRequest overheadPrefer short lifetimes; keep values small

Lifetime attributes themselves are cheap. The cost is cookies riding on every matching request — keep durations short and values small. For client-only data, consider localStorage instead of long-lived cookies.

Key Takeaways

  • Role: expires / max-age control how long a cookie lives.
  • Prefer max-age: relative seconds, less error-prone than UTC date strings.
  • Delete: overwrite with max-age=0 and the same path.
  • Re-send lifetime: updates without it silently become session cookies.

One line: use max-age for persistence, omit lifetime for session UI flags, and delete with max-age=0 + matching path.

Frequently Asked Questions

Both set cookie lifetime. expires is an absolute UTC date string (toUTCString). max-age is relative seconds from now. Prefer max-age — it is simpler and takes precedence if both are set.
A cookie set without expires or max-age. Browsers normally remove it when the session ends, but session restore can keep it — do not treat “session” as a security guarantee.
Overwrite it with the same name and path, setting max-age=0 (or a past expires date). Example: document.cookie = "name=; path=/; max-age=0".
No. document.cookie returns only name=value pairs. Check Expires / Max-Age in DevTools under Application → Cookies.
It becomes a session cookie, even if the previous version was persistent. Always re-send lifetime attributes when updating.
604800 seconds (7 × 24 × 60 × 60). Common values: 1 hour = 3600, 1 day = 86400, 30 days = 2592000.

Next: Cookie Path

Learn how path=/ and section prefixes control where cookies are sent and read.

Cookie Path tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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