JS: Get Cookie, Set Cookie

By Xah Lee. Date: . Last updated: .

This page tells you how to get/set cookies using JavaScript, how to check if cookie is enabled, and how http cookie works.

Firefox show cookie 2014-03-04
Firefox preference pane, showing cookie.

What's a Cookie?

HTTP cookie is a mechanism to store data in a web browser for a website, for the purpose of persistent data.

Persistent data is needed for things like login status, session, tracking user/account, shopping cart.

For example, when you login to a site, the site send you a cookie “loggedin=true”. Your browser stores that together with the website that sent it. When you click a link to see another page on the site, the browser sends all cookies that came from the website, so the server knows you are already logged in, so won't ask you to login.

A cookie is a piece of arbitrary string, but typically having the form "key=value".

The most frequently used info stored in cookies, is a id string to identify user, and a session id. The server usually stores other info about the user in database.

Cookie in HTTP Message Header

Cookie mechanism is part of the HTTP protocol. It is sent as part of HTTP message header. [see HTTP Protocol Tutorial]

When server responds to a HTTP request, it can send cookies in the HTTP header, and browser will store them locally. And everytime browser sends a HTTP request, it must also send all existing cookies of the same domain to the server in the HTTP request header.

Here's a example from Wikipedia HTTP cookie:

GET /index.html HTTP/1.1
Host: www.example.org
browser's HTTP request header
HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: name=value
Set-Cookie: name2=value2; Expires=Wed, 09 Jun 2021 10:18:14 GMT
server's HTTP response header, including 2 lines of cookie

When browser send request for a URL, it also sends all cookies stored locally that matches the domain. Example:

GET /spec.html HTTP/1.1
Host: www.example.org
Cookie: name=value; name2=value2
Accept: */*

View Cookie in HTTP Header

Here's a example of cookie from Apple website:

http protocol headers cookie 2016-04-02 2
Cookie in HTTP header. [see HTTP Protocol Tutorial]

Cookies Using JavaScript

JavaScript can also be used to read or set a cookie. When the server sends a HTML, it can include JavaScript like this:


When browser receives that page and runs the script, it'll set the cookie.

Check Cookie is Enabled

Browsers have a preference setting that allow users to disable cookies.

navigator.cookieEnabled → returns true if cookies is enabled. Else, false.

The navigator.cookieEnabled is supported by all major browsers.

Note: When cookie is disable in browser, webstorage is also disabled.

[see JS: Web Storage Tutorial]

Set a Cookie

To set a cookie, do:

document.cookie = "key=value"

// setting cookies

document .cookie="name=Jack;max-age=259200;path=/";
document .cookie="age=29";
document .cookie="name=Mary"; // same key overrides previous value

// show cookies
console.log(document .cookie);

You can play with cookies by paste the above code in browser console. [see JS: How to Use Browser Console]

Cookie value string cannot contain {comma, semicolon, whitespace}. You can use encodeURIComponent(). [see JS: Encode URL, Escape String]

Cookie Attributes

Each cookie has a set of predefined “attributes” associated with it. The attributes tells browser whether a cookie should be send to the server, when browser requests a page.

Each attribute is a key/value pair. If a attribute is not specified, it has a default value.

cookie attributes
path=pathPath associated with the cookie. (for example, "/", "/img"). If not specified, defaults to the current path of the current document location.
domain=domaindomain name associated with the cookie. (for example, example.com, .example.com, some.example.com) If not specified, defaults to the host portion of the request url, for example c.b.a.example.com. When browser requests a URL, it matches the host name in URL to the ones in local cookies. If any cookie's host name is a subdomain of the host name in URL, that cookie is sent. (provided that the path attribute also passes)
max-age=nn is a integer. Number of seconds into the future when the cookie will expire. This is intented to replace the harder to use “expires=” attribute. “max-age” is not supported by Internet Explorer 8 or before. If both “max-age” and “expires” are set, the “expires” is ignored. If none of “max-age” and “expires” are specified, the browser will delete the cookie when user closes browser. (a session cookie)
expires=dateIf not specified it will expire at the end of session. The date must be in a format same as date.toUTCString(). Example: "Tue, 26 Apr 2016 23:52:26 GMT" [see JS: Date Object]
secureIf present, it means this cookie will only be transmitted from HTTPS access.

Cookie Count and Size Limitation

Cookie has a limitation on total number of cookies per domain, and total size of all cookies combined per domain.

Get Cookie Values

document.cookie → A property that holds a string containing a semicolon-separated list of cookies, of the form key1=value1;key2=value2;….

// show all cookies for the domain
console.log(document .cookie);

play with browser console here JavaScript test: show all cookies

cookie attributes are not returned.

Google chrome browser web dev tool show cookie 2014-03-04 65194
value of document.cookie in Google Chrome browser developer console.

Show Stored Cookies in Browser

You can use browser to show cookies. In Google Chrome browser, it's under 〖Developer Tools〗. In Firefox, it's under 〖Preference ▸ privacy〗. The exact menu location or key may change from version to version.

Google chrome browser web dev tool show cookie 2014-03-04
Google Chrome browser developer tool, showing cookies.

Cookies vs Web Storage

Cookies vs Web Storage, which is better?

Cookies is set/read directly by server in HTTP message exchange.

Web Storage is JavaScript only. (JavaScript in turn, can talk to server, in many flexible ways.)

Both Cookies and Web Storage can be read/set by JavaScript on the client side.

HTTP Cookie is designed around 1995, and is a hack, and its age shows. Web Storage was designed about a decade later and is much more efficient and clean.

If you need server to directly access (read/set) stored data on client side, then use cookie. Otherwise, use web storage.

[see JS: Web Storage Tutorial]


Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials