Back to Home

Cookies, document.cookie

Cookies are small strings of data that are stored directly in the browser. They are a part of the HTTP protocol, defined by the RFC 6265 specification. Cookies are usually set by a web server using the response Set-Cookie HTTP header. Then, the browser automatically adds them to (almost) every request to the same domain using the Cookie HTTP header. One of the most widespread use cases is authentication: 1. Upon sign-in, the server uses the Set-Cookie HTTP header in the response to set a cookie with a unique “session identifier”. 2. Next time the request is sent to the same domain, the browser sends the cookie over the net using the Cookie HTTP header. 3. So the server knows who made the request. We can also access cookies from the browser, using document.cookie property. There are many tricky things about cookies and their attributes. In this chapter, we’ll cover them in detail.

Reading from document.cookie

The value of document.cookie consists of name=value pairs, delimited by ; . Each one is a separate cookie. To find a particular cookie, we can split document.cookie by ; , and then find the right name. We can use either a regular expression or array functions to do that. We leave it as an exercise for the reader. Also, at the end of the chapter, you’ll find helper functions to manipulate cookies.

Writing to document.cookie

We can write to document.cookie. But it’s not a data property, it’s an accessor (getter/setter). An assignment to it is treated specially. A write operation to document.cookie updates only the cookie mentioned in it and doesn’t touch other cookies. For instance, this call sets a cookie with the name user and value John: If you run it, you will likely see multiple cookies. That’s because the document.cookie= operation does not overwrite all cookies. It only sets the mentioned cookie user. Technically, name and value can have any characters. To keep the valid formatting, they should be escaped using a built-in encodeURIComponent function: Cookies have several attributes, many of which are important and should be set. The attributes are listed after key=value, delimited by ;, like this:

domain

  1. The HTTP method is “safe” (e.g. GET, but not POST). The full list of safe HTTP methods is in the RFC7231 specification. These are the methods that should be used for reading, but not writing the data. They must not perform any data-changing operations. Following a link is always GET, the safe method.
  2. The operation performs a top-level navigation (changes URL in the browser address bar). This is usually true, but if the navigation is performed in an