Cookie attributes are additional parameters that can be set when creating or updating a cookie. These attributes provide control over various aspects of the cookie’s behavior, such as its expiration, domain, path, security, and accessibility.
Common Cookie Attributes:
Expires:
- Specifies the expiration date and time for the cookie. Once the expiration date is reached, the browser automatically deletes the cookie.
- Example:
"expires=Thu, 18 Dec 2024 12:00:00 UTC"
Max-Age:
- Specifies the maximum age of the cookie in seconds. After the specified time period elapses, the browser deletes the cookie.
- Example:
"max-age=3600"
(sets the cookie to expire in 1 hour)
Domain:
- Specifies the domain for which the cookie is valid. By default, the cookie is only sent to the domain that set it, but you can specify a broader domain to include subdomains.
- Example:
"domain=example.com"
Path:
- Specifies the path within the domain for which the cookie is valid. By default, the cookie is only sent to the path of the current page, but you can specify a broader or narrower path.
- Example:
"path=/"
(cookie is sent to all pages within the domain)
Secure:
- Specifies whether the cookie should only be sent over secure HTTPS connections. This attribute helps prevent the cookie from being intercepted by unauthorized parties.
- Example:
"secure"
HttpOnly:
- Specifies whether the cookie is accessible only through HTTP requests and not through JavaScript. This attribute helps mitigate certain types of cross-site scripting (XSS) attacks by preventing client-side scripts from accessing the cookie.
- Example:
"httponly"
document.cookie = "username=John Doe;
expires=Thu, 18 Dec 2024 12:00:00 UTC;
path=/; domain=example.com; secure; httponly";
Notes:
- When setting multiple attributes, separate them with semicolons (
;
) within the cookie string. - Not all attributes are supported by all browsers, and some attributes may have limitations or specific requirements.
- Cookie attributes provide control over the cookie’s behavior and security, allowing developers to tailor cookies to specific use cases and security requirements.