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.

What is 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 line of text, 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.

Cookie is Sent 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 includes cookies (if any) in the response HTTP header, and browser store them locally.

Everytime browser sends a HTTP request, it also send all existing cookies of the same domain to the server in the HTTP request header.

Here is a example of browser's HTTP request header:

GET /index.html HTTP/1.1
Host: www.example.org

Here's example: of server's HTTP response header, including 2 lines of cookie:

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

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

here's example:

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

View Cookie in HTTP Header in Browser Dev Tool

Browser dev tool can view HTTP Headers.

Here is a real world cookie from apple.com:

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

Check Cookie is Enabled

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

navigator.cookieEnabled
Return true if cookies is enabled. Else, false.

Get/Set Cookies with JavaScript

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

document.cookie="c1=3"

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

Set Cookie

To set a cookie, do:

document.cookie = "key=value"

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

Get Cookie

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

You can play with cookies by paste the above code in browser console.

[see How to Use Browser Console]

Cookie value string cannot contain {comma, semicolon, whitespace}. You can use encodeURIComponent(). [see 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.

path=path
Path associated with the cookie. (e.g. "/", "/img"). If not specified, defaults to the current path of the current document location.
domain=domain
domain name associated with the cookie. (e.g. 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=n
n 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=date
If 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 Date Object]
secure
If 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);

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.

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

[see How to Use Browser Console]

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. Web Storage was designed about 10 years later and is much more efficient and clean.

If you need web server to directly read/set data on browser, then use cookie. Otherwise, use web storage.

[see Web Storage]

BUY ΣJS JavaScript in Depth