
Cookie Attributes
When working with cookies in JavaScript, you can set various attributes to control their behavior. Here are some common cookie attributes:
1. Expiration (Expires or Max-Age): You can set an expiration date or maximum age for the cookie, after which it will be automatically deleted by the browser. The expiration can be specified using either the Expires
attribute or the Max-Age
attribute.
Expires
: Sets an absolute expiration date for the cookie. The value should be a string in the format “Day, DD Mon YYYY HH:MM:SS GMT”. For example:
document.cookie = "username=John Doe; expires=Fri, 31 Dec 2023 23:59:59 GMT";
Max-Age
: Sets the maximum age of the cookie in seconds. The cookie will be deleted by the browser after the specified duration has elapsed. For example, to set a cookie that expires in 1 day:
javascript document.cookie = "username=John Doe; max-age=" + (60 * 60 * 24);
2. Domain: You can specify the domain for which the cookie is valid. By default, cookies are valid for the current domain. To make the cookie valid for a specific domain and its subdomains, set the Domain
attribute. For example:
document.cookie = "username=John Doe; domain=example.com";
Path: You can set the path for which the cookie is valid. By default, cookies are valid for the current path. To make the cookie valid for a specific path, set the Path
attribute. For example, to make the cookie valid for the entire website:
document.cookie = "username=John Doe; path=/";
Secure: By setting the Secure
attribute, the cookie will only be sent over secure HTTPS connections. It ensures that the cookie is not transmitted over unsecured HTTP connections. For example:
document.cookie = "username=John Doe; secure";
SameSite: The SameSite
attribute specifies whether the cookie should be sent with cross-site requests. It helps protect against certain types of cross-site request forgery (CSRF) attacks. There are three possible values for SameSite
:
None
: The cookie will be sent with both same-site and cross-site requests.Strict
: The cookie will only be sent with same-site requests.Lax
: The cookie will be sent with same-site requests and cross-site requests initiated by navigating to the target URL. For example, to set theSameSite
attribute toStrict
:
document.cookie = "username=John Doe; samesite=strict";
These are some of the common attributes used with cookies in JavaScript. Note that not all attributes are supported in all browsers, especially older ones. It’s recommended to test your code across different browsers to ensure compatibility.