HTML DOM Document cookie attribute

Definition and Usage

cookie Properties set or returned as a semicolon-separated key=value List of (document cookies).

Example of creating a cookie:

document.cookie="username=Bill Gates; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Tip:Cookies cannot contain commas, semicolons, or spaces.The encodeURIComponent() method can ensure that they will not.

See also:

JavaScript Cookies Tutorial

Recommendation:

Sometimes the Storage API is a better tool:

localStorage property

sessionStorage property

Example

Get all cookies associated with this document:

let allCookies = document.cookie;

Try it yourself

Syntax

Return cookie:

document.cookie

Set cookie:

document.cookie = newCookie

parameters

separated by semicolons name=value For the list, followed by any optional values:

expires=date
GMT date format (using the Date.toUTCString method).
Default value: delete the cookie when the browser is closed.
max-age=seconds
The maximum age before deleting the cookie. Delete the cookie if it is 0 or a past date.
path=path
The absolute path of the directory to which the cookie belongs ('/dir'). Default value: the current directory.
domain=domainname
Domain of the site ('example.com'). Default value: the domain of the document.
secure
Send cookies to the server using a secure protocol (https).

return value

type description
string separated by semicolons key=value for the list (document cookie).

Cookie and local storage

Cookies are used for client-server (browser-server) applications.

Local storage (Local Storage) is used for client (browser) applications.

Cookies are associated with websites. Sending cookies in each HTTP header is a waste of bandwidth if the data is intended for client use.

Some users' browsers usually disable cookies.

The size limit for cookies is 4 KB. Each domain in local storage is limited to 5 megabytes.

Cookies have an expiration date. Local storage does not.

Browser support

document.cookie is a DOM Level 2 (2001) feature.

All browsers support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
support 9-11 support support support support