HTML DOM Document cookie
Example
Get all cookies associated with this document:
let allCookies = document.cookie;
Try it Yourself »
Definition and Usage
The cookie
property sets or returns a semicolon-separated list of key=value pairs (document cookies).
An example of creating a cookie:
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC;
path=/";
Note
Cookies cannot contain commas, semicolons or whitespaces.
The encodeURIComponent() Method ensures they don't.
See Also:
Advice:
Somtimes the Storage API is a better tool:
Syntax
Return the cookie:
document.cookie
Set the cookie:
document.cookie = newCookie
Parameter
A semicolon-separated list of name=value pairs, followed with any of thise optional values:
expires=date max-age=seconds path=path domain=domainname secure |
Return Value
Type | Description |
String | A semicolon-separated list of key=value pairs (document cookies). |
Cookies vs Local Storage
Cookies are for client-server (browser-server) applications.
Local storage are for client (browser) applications.
Cookies are associated with websites. If the data is for client use, sending cookies in every HTTP header is waste of bandwith.
Some users have cookies disabled as a rule in their browsers.
A Cookie has a size limit of 4 Kilobytes. Local Storage has a limit of 5 Megabytes per domain.
A Cookie have expiration date. Local Storage has not.
Browser Support
document.cookie
is a DOM Level 2 (2001) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |