Proper Methods and Practical Guide for Setting Cookie Expiration Time in JavaScript

Nov 20, 2025 · Programming · 11 views · 7.8

Keywords: JavaScript | Cookie | Expiration | Expires | Max-Age

Abstract: This article provides an in-depth exploration of common issues and solutions for setting cookie expiration times in JavaScript. Through analysis of actual code examples, it explains the differences and usage methods between Expires and Max-Age attributes, offers multiple practical solutions for setting cookie expiration times, and compares the advantages and disadvantages of different approaches. The article also covers key knowledge points including cookie security settings and browser compatibility, providing comprehensive technical reference for developers.

Problem Background and Common Misconceptions

In web development, cookies are essential mechanisms for maintaining user session states. However, many developers encounter various issues when setting cookie expiration times. According to actual cases from Stack Overflow, a common problem is that set expiration times don't seem to take effect, with cookies still behaving as session cookies.

Analysis of Original Problem Code

The original code provided by the user was:

var now = new Date();
var time = now.getTime();
var expireTime = time + 1000*60;
now.setTime(expireTime);
var tempExp = 'Wed, 31 Oct 2012 08:50:17 GMT';
document.cookie = aaa+'='+sStr+';expires='+now.toGMTString()+';path=/';

This code has several potential issues: first, the expiration time calculation may not be accurate enough; second, using the toGMTString() method may behave inconsistently across different browsers; finally, the hard-coded expiration time string format may not comply with specifications.

Optimal Solution

According to the highest-rated answer, the correct implementation is as follows:

function display() { 
  var now = new Date();
  var time = now.getTime();
  var expireTime = time + 1000*36000;
  now.setTime(expireTime);
  document.cookie = 'cookie=ok;expires='+now.toUTCString()+';path=/';
}

The key improvements in this solution include:

Comparison Between Expires and Max-Age Attributes

According to HTTP specifications, there are two main ways to set cookie expiration times:

Using Expires Attribute

var expires = (new Date(Date.now()+ 86400*1000)).toUTCString();
document.cookie = "cookieName=cookieValue; expires=" + expires + ";path=/;"

Using Max-Age Attribute

document.cookie = "cookieName=cookieValue; max-age=86400; path=/;";

The main difference between the two is that Expires sets an absolute time, while Max-Age sets a relative time (in seconds). When both are present, Max-Age takes precedence.

Practical Function Encapsulation

For convenient reuse, a general cookie setting function can be encapsulated:

function writeCookie(key, value, days) {
    var date = new Date();
    days = days || 365;
    date.setTime(date.getTime() + (days * 86400000));
    document.cookie = key + "=" + value + "; expires=" + date.toUTCString() + "; path=/";
    return value;
}

Cookie Security and Best Practices

According to HTTP Set-Cookie specifications, the following security factors should be considered when setting cookies:

Secure Attribute

Ensure cookies are only transmitted over HTTPS connections:

document.cookie = "name=value; Secure; path=/";

HttpOnly Attribute

Prevent JavaScript from accessing sensitive cookies, mitigating XSS attack risks:

// Note: HttpOnly attribute can only be set on the server side

SameSite Attribute

Control whether cookies are sent with cross-site requests:

document.cookie = "name=value; SameSite=Strict; path=/";

Browser Compatibility Considerations

Different browsers have varying levels of support for cookie attributes:

Common Issue Troubleshooting

If cookie settings still don't take effect, check the following aspects:

  1. Whether the time format is correct (must use UTC/GMT format)
  2. Whether path and domain settings match the current page
  3. Whether cookies are enabled in the browser
  4. Whether unsupported characters are used (such as semicolons, commas, etc.)

Conclusion

Properly setting cookie expiration times requires comprehensive consideration of multiple factors including time format, browser compatibility, and security requirements. By using standard time formats, reasonable expiration time calculations, and appropriate security attributes, cookies can be ensured to work properly across various environments. Developers are recommended to encapsulate general cookie operation functions in actual projects to improve code maintainability and security.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.