Cookie Expiration and Max-Age
What you'll learn: How to control when cookies are automatically deleted by setting their lifetime using expires and max-age attributes.
By default, cookies you create are session cookies—they vanish when the browser closes. But often you want cookies to persist longer (or expire sooner). That's where expiration settings come in.
Two Ways to Set Cookie Lifetime
When setting a cookie with document.cookie, you can add attributes to control how long it lives:
1. The expires Attribute
This sets an absolute expiration date and time. Think of it like writing "Best by: December 31, 2025" on a food label.
// Cookie expires on a specific date
document.cookie = "username=Sarah; expires=Fri, 31 Dec 2025 23:59:59 GMT";
You must format the date as a UTC string (use toUTCString() on a Date object).
2. The max-age Attribute
This sets a relative lifetime in seconds from now. It's like saying "This expires in 7 days" rather than picking a calendar date.
// Cookie expires in 7 days (604800 seconds)
document.cookie = "username=Sarah; max-age=604800";
// Cookie expires in 1 hour (3600 seconds)
document.cookie = "theme=dark; max-age=3600";
Which Should You Use?
max-age is simpler and more modern—it automatically calculates the expiration time. expires requires you to manually create and format dates. If both are set, max-age takes precedence.
Deleting Cookies
To delete a cookie, set max-age=0 or expires to a past date:
document.cookie = "username=Sarah; max-age=0"; // Gone immediately
Key Takeaway: Use max-age with a value in seconds for simple relative expiration, or expires with a UTC date string for absolute expiration—without either, your cookie only lasts until the browser closes.