13. februar 2024
Dette materiale er kun tilgængeligt på følgende sprog: عربي, Čeština, English, Español, فارسی, Français, Indonesia, Italiano, 日本語, 한국어, Русский, Türkçe, Українська, Oʻzbek, 简体中文. Hjælp os med at oversætte til Dansk.

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

Does your browser store any cookies from this site? Let’s see:

// At javascript.info, we use Google Analytics for statistics,
// so there should be some cookies
alert( document.cookie ); // cookie1=value1; cookie2=value2;...

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:

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies

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: