HTML DOM Document cookie

Example

Get all cookies associated with this document:

let allCookies = document.cookie;
Try it Yourself »

Description

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:

JavaScript Cookies Tutorial

Advice:

Somtimes the Storage API is a better tool:

The localStorage Property

The sessionStorage Property



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
A date in GMT format (Use the Date.toUTCString method).
Default value: The cookie is deleted when the browser is closed.

max-age=seconds
The max age before the cookie is deleted.
If to 0 or a date in the past, the cookie is deleted.

path=path
An absoulute path to the directory the cookie belongs to ('/dir').
Default value: Current directory.

domain=domainname
The domain of the site ('example.com').
Default value: The domain of the document.

secure
Use a secure protocol (https) for sending the cookie to the server.

Return Value

Type Description
StringA 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


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.