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
Fundamentals
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.
Concept
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.
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
Behavior
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.
Read
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.
Hands-On
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);
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);
Centralizing lifetime logic prevents accidental session downgrade on updates. Pass days only when you need persistence.
Applications
🚀 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.
Important
📝 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 mismatch — max-age=0 must use the same path as the original.
No expiry in reads — document.cookie hides expiration metadata.
Negative max-age — treated as delete (0 or past expiry).
Compatibility
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 ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
expires / max-ageExcellent
Bottom line: Use max-age for new code. Verify deletion and persistence in DevTools when cookies behave unexpectedly.
Wrap Up
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.
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.