JavaScript Cookies — Expires & max-age

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Cookie lifetime

What You’ll Learn

Cookie lifetime controls how long data survives in the browser. This tutorial covers expires and max-age, session cookies, deleting expired entries, and keeping persistence when you update values.

01

Session

No expiry attrs

02

expires

UTC date string

03

max-age

Seconds from now

04

Delete

max-age=0

05

Refresh

Sliding sessions

06

DevTools

Expiry not in script

Introduction

Without a lifetime attribute, cookies die when the browser session ends. With expires or max-age, they become persistent—surviving restarts until they expire or you delete them.

Choosing the right lifetime balances convenience (remember my theme) against privacy and security (short-lived session tokens). Always pair lifetime attributes with path=/ unless you intentionally scope narrower—see Path attribute.

What Are Cookies in JavaScript?

Cookies store small name–value pairs via document.cookie. They can hold preferences, cart hints, or consent flags—not passwords or raw auth secrets in script-readable form.

Lifetime is controlled by optional attributes:

  • Neither set — session cookie (temporary).
  • expires — absolute expiry instant in UTC text form.
  • max-age — relative lifetime in seconds (recommended).
💡
Beginner Tip

When both Max-Age and Expires are present, modern browsers prefer Max-Age. Pick one style in your code—max-age is usually simpler.

📝 Syntax

Persistent cookie with expires (7 days from now):

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

document.cookie = "username=JohnDoe; " + expires + "; path=/";

Same duration with max-age (preferred):

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

document.cookie = "username=JohnDoe; max-age=" + sevenDays + "; path=/";

Session cookie (no lifetime attributes):

JavaScript
document.cookie = "flash=seen; path=/";

⚡ Quick Reference

GoalAttribute
Session cookieOmit expires and max-age
7 days persistentmax-age=604800
1 hourmax-age=3600
30 daysmax-age=2592000
Delete cookiemax-age=0 + same path
Read expiry in JSNot available — use DevTools

📋 expires vs max-age

Both make cookies persistent. Choose based on how you think about time—absolute clock vs relative duration.

expires
toUTCString()

Fixed calendar date

max-age
604800

Seconds from set time

Session
(none)

Until browser closes

Delete
max-age=0

Immediate removal

How Cookie Expiration Works

When a cookie expires—by time or explicit deletion—the browser removes it. Expired cookies do not appear in document.cookie and are not sent on HTTP requests.

Reading cookies returns values only; you cannot ask JavaScript when a cookie expires. Use DevTools or server logs for auditing lifetimes.

When updating, re-send max-age or expires. Omitting them converts a persistent cookie into a session cookie.

Reading Cookies (Without Expiration Info)

document.cookie never includes expiry metadata. To read values, use a parser from the Read cookies guide:

JavaScript
console.log(document.cookie); // "username=JohnDoe" — no expires shown

function getCookie(name) {
  const pairs = document.cookie.split(";");
  for (const pair of pairs) {
    const trimmed = pair.trim();
    const eq = trimmed.indexOf("=");
    if (eq === -1) continue;
    if (trimmed.slice(0, eq) === name) {
      return trimmed.slice(eq + 1);
    }
  }
  return null;
}

If getCookie returns null, the cookie may be expired, scoped to another path, HttpOnly, or never set.

Examples Gallery

Inspect cookies in DevTools → Application → Cookies (Expires / Max-Age column). Try-it labs demonstrate each lifetime pattern.

📚 Getting Started

Set persistent cookies with calendar-based expiry.

Example 1 — Set Cookie with expires (7 Days)

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

JavaScript
function setCookieExpires(name, value, days) {
  const date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  document.cookie = name + "=" + encodeURIComponent(value) +
    "; expires=" + date.toUTCString() +
    "; path=/; SameSite=Lax";
}

setCookieExpires("username", "JohnDoe", 7);
console.log(document.cookie);
Try It Yourself

How It Works

The browser stores the cookie until the UTC instant in expires. Always use toUTCString() (or equivalent UTC formatting) to avoid local timezone bugs.

📈 Practical Patterns

max-age, sessions, deletion, and reusable helpers.

Example 2 — Prefer max-age for Relative Durations

Set a 7-day cookie without date math strings.

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

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

// Refresh sliding session — same max-age resets the countdown
document.cookie = "prefs=compact; max-age=" + sevenDays + "; path=/; SameSite=Lax";
Try It Yourself

How It Works

max-age counts seconds from the moment the cookie is written. Re-writing the same cookie with a new max-age implements sliding expiration for active users.

Example 3 — Session Cookie (No Expiration)

Temporary flag cleared when the browser session ends.

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

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

How It Works

Session cookies suit short-lived UI state. Do not rely on them for long-term storage—users lose them when closing the browser.

Example 4 — Delete a Cookie with max-age=0

Remove a cookie by overwriting with zero lifetime and matching path.

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

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

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

How It Works

Deletion is a write with empty value and immediate expiry. The path (and domain if used) must match the original cookie.

Example 5 — setCookieWithExpiry Helper

One function supporting days-based persistence or session mode.

JavaScript
function setCookieWithExpiry(name, value, days) {
  const encoded = encodeURIComponent(value);
  let cookie = name + "=" + encoded + "; path=/; SameSite=Lax";
  if (typeof days === "number" && days > 0) {
    cookie += "; max-age=" + (days * 24 * 60 * 60);
  }
  document.cookie = cookie;
}

setCookieWithExpiry("username", "JohnDoe", 7);  // persistent
setCookieWithExpiry("flash", "ok");            // session (no days)
Try It Yourself

How It Works

Centralizing lifetime logic prevents accidental session downgrade on updates. Pass days only when you need persistence.

🚀 Common Use Cases

  • Remember me — 30-day max-age for display name (not passwords).
  • Consent banner — 1-year persistence for analytics consent.
  • Flash messages — session cookie to hide a one-time alert.
  • Sliding sessions — refresh hourly max-age on activity.
  • Logout — delete auth-related cookies with max-age=0.
  • Short-lived carts — 7-day expiry for anonymous cart IDs.

🧠 Cookie Lifetime Timeline

1

Write cookie

Include max-age/expires for persistent, or omit for session.

Create
2

Browser stores

Cookie jar records expiry instant or session flag internally.

Store
3

Active period

Value readable via script and sent on HTTP requests while valid.

Live
4

Expiry or delete

Time passes or max-age=0 runs → cookie removed automatically.

📝 Notes & Common Pitfalls

  • Bad date format — non-UTC expires strings may be ignored.
  • Timezone confusion — prefer max-age over manual date strings.
  • Update without expiry — downgrades persistent cookies to session cookies.
  • Delete path mismatchmax-age=0 must use the same path as the original.
  • No expiry in readsdocument.cookie hides expiration metadata.
  • Negative max-age — treated as delete (0 or past expiry).

Browser Support

expires and max-age are standard cookie attributes supported everywhere document.cookie works, including Internet Explorer.

Baseline · DOM Level 0

Cookie expires & max-age

Universal in Chrome, Firefox, Safari, Edge, and IE. max-age is supported in all modern browsers; expires remains widely used for legacy compatibility.

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: Use max-age for new code. Verify deletion and persistence in DevTools when cookies behave unexpectedly.

Conclusion

Cookie expiration turns temporary browser memory into controlled persistence. Use session cookies for short UI state, max-age for durable preferences, and max-age=0 to delete.

Always re-apply lifetime attributes when updating, and inspect expiry in DevTools because JavaScript reads cannot see it.

💡 Best Practices

✅ Do

  • Prefer max-age for relative lifetimes
  • Use UTC with expires when required
  • Re-send expiry on every update
  • Delete with matching path=/
  • Keep sensitive tokens HttpOnly + short-lived

❌ Don’t

  • Hard-code past calendar dates in tutorials
  • Assume reads expose expiration
  • Store passwords in long-lived cookies
  • Omit expiry on persistent updates
  • Use extremely long max-age without reason

Key Takeaways

Knowledge Unlocked

Five things to remember about cookie expiration

Control persistence safely from JavaScript.

5
Core concepts
📅 02

expires

UTC date string.

Absolute
🕐 03

max-age

Seconds count.

Relative
🗑 04

Delete

max-age=0.

Remove
🔍 05

Hidden

Not in reads.

DevTools

❓ Frequently Asked Questions

Both set cookie lifetime. expires is an absolute UTC date string; max-age is relative seconds from now. Prefer max-age for simpler math—avoid timezone mistakes.
A cookie set without expires or max-age. It is removed when the browser session ends (typically when all tabs for that profile close).
Overwrite it with the same name and path, setting max-age=0 or expires to a past UTC date. Example: document.cookie = "name=; path=/; max-age=0".
No. document.cookie returns only name=value pairs. Check expiration in DevTools under Application → Cookies.
The cookie becomes a session cookie, even if the old version was persistent. Always re-send lifetime attributes when updating.
604800 seconds (7 × 24 × 60 × 60). Common durations: 1 hour = 3600, 1 day = 86400, 30 days = 2592000.
Did you know?

Deleting a cookie is not a separate API—you overwrite it with an empty value and max-age=0 (or a past expires date) using the same name and path as the original.

Continue to Path Attribute

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

Path attribute 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