JavaScript Cookie Attributes
Syntax
document.cookie = "name=value; attribute1=value1; attribute2=value2; ..."
where,
name
is the name of the cookievalue
is the value of the cookieattribute1
,attribute2
,... are the different attributes associated with the cookie.
Example
Let's create a cookie with name "username" and value "John" and add the attribute "expires" to it with a value of 10 days from now.
document.cookie = "username=John; expires=" + new Date(new Date().getTime() + 10 * 24 * 60 * 60 * 1000).toUTCString();
Output
A cookie with name "username" will be created with a value of "John" and will expire 10 days from the current date.
Explanation
Cookies are small text files that websites use to store information on a user's computer. They are commonly used to identify and track users, remember user preferences and login details, and provide personalized content.
JavaScript provides several attributes that can be associated with cookies to customize their behavior. These attributes include expires
, path
, domain
, secure
, and samesite
.
Use
expires
: Specifies the expiration date and time for the cookie. The cookie will be deleted after this date. If theexpires
attribute is not set, the cookie will be deleted when the browser is closed.path
: Specifies the path for which the cookie is valid. By default, cookies are valid for the current page only.domain
: Specifies the domain for which the cookie is valid. By default, cookies are valid for the current domain only.secure
: Specifies that the cookie can only be sent over a secure (HTTPS) connection.samesite
: Specifies whether the cookie can be sent when making cross-site requests. The possible values arestrict
,lax
, andnone
.
Important Points
- The
name
andvalue
arguments must be URL-encoded before they are sent to the server. - Cookies are limited in size to 4096 bytes.
- The number of cookies that a website can store on a user's computer is also limited (usually to 20 cookies per domain).
- Cookies can be deleted by setting their
expires
attribute to a date in the past.
Summary
In this article, we learned about the different attributes that can be associated with JavaScript cookies like expires
, path
, domain
, secure
, and samesite
. These attributes allow us to customize the behavior of cookies and make them more secure. We also saw an example of how to create a cookie with an expiration date using JavaScript.