Cookie Format

broken image


Path: the root path under the domain where the cookie is valid. If this is /, the cookie is valid for the entire domain. Secure Flag: either TRUE or FALSE, whether or not a secure connection (HTTPS) is required to read the cookie. Expiration Timestamp: the 'Unix Time' in seconds when the cookie is set to expire. The cookie expiration date defines the time, when the browser will automatically delete it. The date must be exactly in this format, in the GMT timezone. We can use date.toUTCString to get it. For instance, we can set the cookie to expire in 1 day. Each cookie must have the following format: CookieN(cookielength,URLlength)cookietext,validationURL Cookie A required keyword that indicates the start of a cookie entry. The Cookie keyword cannot contain blanks and it must have a single digit appended to it, either 0, 1, or 2. According to the Microsoft Developer Network, HttpOnly is an additional flag included in a Set-Cookie HTTP response header. Using the HttpOnly flag when generating a cookie helps mitigate the risk of client side script accessing the protected cookie (if the browser supports it). The example below shows the syntax used within the HTTP response.

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 when 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 options. 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:

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 cookies mentioned in it, but doesn't touch other cookies.

For instance, this call sets a cookie with the name user and value John:

If you run it, then probably you'll 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:

There are few limitations:

  • The name=value pair, after encodeURIComponent, should not exceed 4KB. So we can't store anything huge in a cookie.
  • The total number of cookies per domain is limited to around 20+, the exact limit depends on the browser.

Cookies have several options, many of them are important and should be set.

The options are listed after key=value, delimited by ;, like this:

path

  • path=/mypath

The url path prefix must be absolute. It makes the cookie accessible for pages under that path. By default, it's the current path.

If a cookie is set with path=/admin, it's visible at pages /admin and /admin/something, but not at /home or /adminpage.

Usually, we should set path to the root: path=/ to make the cookie accessible from all website pages.

domain

  • domain=site.com

A domain defines where the cookie is accessible. In practice though, there are limitations. We can't set any domain.

By default, a cookie is accessible only at the domain that set it. So, if the cookie was set by site.com, we won't get it at other.com.

…But what's more tricky, we also won't get the cookie at a subdomain forum.site.com!

There's no way to let a cookie be accessible from another 2nd-level domain, so other.com will never receive a cookie set at site.com.

It's a safety restriction, to allow us to store sensitive data in cookies, that should be available only on one site.

…But if we'd like to allow subdomains like forum.site.com to get a cookie, that's possible. When setting a cookie at site.com, we should explicitly set the domain option to the root domain: domain=site.com:

For historical reasons, domain=.site.com (a dot before site.com) also works the same way, allowing access to the cookie from subdomains. That's an old notation and should be used if we need to support very old browsers.

So, the domain option allows to make a cookie accessible at subdomains.

expires, max-age

By default, if a cookie doesn't have one of these options, it disappears when the browser is closed. Such cookies are called 'session cookies'

To let cookies survive a browser close, we can set either the expires or max-age option.

  • expires=Tue, 19 Jan 2038 03:14:07 GMT

The cookie expiration date defines the time, when the browser will automatically delete it.

The date must be exactly in this format, in the GMT timezone. We can use date.toUTCString to get it. For instance, we can set the cookie to expire in 1 day:

If we set expires to a date in the past, the cookie is deleted.

  • max-age=3600

Is an alternative to expires and specifies the cookie's expiration in seconds from the current moment.

If set to zero or a negative value, the cookie is deleted:

secure

  • secure

The cookie should be transferred only over HTTPS.

By default, if we set a cookie at http://site.com, then it also appears at https://site.com and vice versa.

That is, cookies are domain-based, they do not distinguish between the protocols.

With this option, if a cookie is set by https://site.com, then it doesn't appear when the same site is accessed by HTTP, as http://site.com. So if a cookie has sensitive content that should never be sent over unencrypted HTTP, the secure flag is the right thing.

samesite

That's another security attribute samesite. It's designed to protect from so-called XSRF (cross-site request forgery) attacks.

To understand how it works and when it's useful, let's take a look at XSRF attacks.

XSRF attack

Imagine, you are logged into the site bank.com. That is: you have an authentication cookie from that site. Your browser sends it to bank.com with every request, so that it recognizes you and performs all sensitive financial operations.

Now, while browsing the web in another window, you accidentally come to another site evil.com. That site has JavaScript code that submits a form

to bank.com with fields that initiate a transaction to the hacker's account.

The browser sends cookies every time you visit the site bank.com, even if the form was submitted from evil.com. So the bank recognizes you and actually performs the payment.

That's a so-called 'Cross-Site Request Forgery' (in short, XSRF) attack.

Real banks are protected from it of course. All forms generated by bank.com have a special field, a so-called 'XSRF protection token', that an evil page can't generate or extract from a remote page. It can submit a form there, but can't get the data back. The site bank.com checks for such token in every form it receives.

Such a protection takes time to implement though. We need to ensure that every form has the required token field, and we must also check all requests.

Enter cookie samesite option

Cookie format string

The cookie samesite option provides another way to protect from such attacks, that (in theory) should not require 'xsrf protection tokens'.

It has two possible values:

Cookie Format

Format

The cookie samesite option provides another way to protect from such attacks, that (in theory) should not require 'xsrf protection tokens'.

It has two possible values:

Cookie Format

  • samesite=strict (same as samesite without value)

A cookie with samesite=strict is never sent if the user comes from outside the same site.

Http Cookie Format

In other words, whether a user follows a link from their mail or submits a form from evil.com, or does any operation that originates from another domain, the cookie is not sent.

If authentication cookies have the samesite option, then a XSRF attack has no chances to succeed, because a submission from evil.com comes without cookies. So bank.com will not recognize the user and will not proceed with the payment.

The protection is quite reliable. Only operations that come from bank.com will send the samesite cookie, e.g. a form submission from another page at bank.com.

Although, there's a small inconvenience.

When a user follows a legitimate link to bank.com, like from their own notes, they'll be surprised that bank.com does not recognize them. Indeed, samesite=strict cookies are not sent in that case.

We could work around that by using two cookies: one for 'general recognition', only for the purposes of saying: 'Hello, John', and the other one for>.

Along with the banner, the remote server at ads.com may set the Set-Cookie header with a cookie like id=1234. Such a cookie originates from the ads.com domain, and will only be visible at ads.com:

Next time when ads.com is accessed, the remote server gets the id cookie and recognizes the user:

What's even more important is, when the user moves from site.com to another site other.com, which also has a banner, then ads.com gets the cookie, as it belongs to ads.com, thus recognizing the visitor and tracking him as he moves between sites:

Third-party cookies are traditionally used for tracking and ads services, due to their nature. They are bound to the originating domain, so ads.com can track the same user between different sites, if they all access it.

Naturally, some people don't like being tracked, so browsers allow to disable such cookies.

Also, some modern browsers employ special policies for such cookies:

  • Safari does not allow third-party cookies at all.
  • Firefox comes with a 'black list' of third-party domains where it blocks third-party cookies.

If we load a script from a third-party domain, like </code>, and that script uses <code>document.cookie</code> to set a cookie, then such cookie is not third-party.</p><p>If a script sets a cookie, then no matter where the script came from – the cookie belongs to the domain of the current webpage.</p><h2>Appendix: GDPR</h2><p>This topic is not related to JavaScript at all, just something to keep in mind when setting cookies.</p><p>There's a legislation in Europe called GDPR, that enforces a set of rules for websites to respect the users' privacy. One of these rules is to require an explicit permission for tracking cookies from the user.</p><p>Please note, that's only about tracking/identifying/authorizing cookies.</p><p>So, if we set a cookie that just saves some information, but neither tracks nor identifies the user, then we are free to do it.</p><p>But if we are going to set a cookie with an authentication session or a tracking id, then a user must allow that.</p><p>Websites generally have two variants of following GDPR. You must have seen them both already in the web:</p><ol><li><p>If a website wants to set tracking cookies only for authenticated users.</p><p>To do so, the registration form should have a checkbox like 'accept the privacy policy' (that describes how cookies are used), the user must check it, and then the website is free to set auth cookies.</p></li><li><p>If a website wants to set tracking cookies for everyone.</p><p>To do so legally, a website shows a modal 'splash screen' for newcomers, and requires them to agree to the cookies. Then the website can set them and let people see the content. That can be disturbing for new visitors though. No one likes to see such 'must-click' modal splash screens instead of the content. But GDPR requires an explicit agreement.</p></li></ol><p>GDPR is not only about cookies, it's about other privacy-related issues too, but that's too much beyond our scope.</p><h2>Summary</h2><p><code>document.cookie</code> provides access to cookies</p><ul><li>write operations modify only cookies mentioned in it.</li><li>name/value must be encoded.</li><li>one cookie must not exceed 4KB, 20+ cookies per site (depends on the browser).</li></ul><p>Cookie options:</p><ul><li><code>path=/</code>, by default current path, makes the cookie visible only under that path.</li><li><code>domain=site.com</code>, by default a cookie is visible on the current domain only. If the domain is set explicitly, the cookie becomes visible on subdomains.</li><li><code>expires</code> or <code>max-age</code> sets the cookie expiration time. Without them the cookie dies when the browser is closed.</li><li><code>secure</code> makes the cookie HTTPS-only.</li><li><code>samesite</code> forbids the browser to send the cookie with requests coming from outside the site. This helps to prevent XSRF attacks.</li></ul><p>Additionally:</p><ul><li>Third-party cookies may be forbidden by the browser, e.g. Safari does that by default.</li><li>When setting a tracking cookie for EU citizens, GDPR requires to ask for permission.</li></ul><p>HTTP cookies are small text files that websites place and store on the computers and mobile devices of their users. These files are generally used to improve the user experience, but may contain personal information about the user or their behavior on the website.</p><p>If your website uses these tracking technologies, you <strong>need</strong> a dedicated cookie policy.</p><p>Download our template below and read our guide to create one for your own website.</p><section><span>Table of Contents</span></section><h2>1. Generic Cookie Policy Template [Download for Free]</h2><h2 id='cookie-format-converter'>Cookie Format Converter</h2><p>Simply click the box below to see an example of a generic cookies policy, or click the button beneath it to download the document in Microsoft Word and PDF file formats.</p><h2>Cookie Policy Template [Text Format]</h2><p>Last updated <span>[month day, year]</span></p><p><strong>INTRODUCTION</strong></p><p><span>[Business Entity Name]</span> ('we' or 'us' or 'our') may use cookies, web beacons, tracking pixels, and other tracking technologies when you visit our website <span>[Name of Website.com]</span>, including any other media form, media channel, mobile website, or mobile application related or connected thereto (collectively, the 'Site') to help customize the Site and improve your experience.</p><p>We reserve the right to make changes to this Cookie Policy at any time and for any reason. We will alert you about any changes by updating the 'Last Updated' date of this Cookie Policy. Any changes or modifications will be effective immediately upon posting the updated Cookie Policy on the Site, and you waive the right to receive specific notice of each such change or modification.</p><p>You are encouraged to periodically review this Cookie Policy to stay informed of updates. You will be deemed to have been made aware of, will be subject to, and will be deemed to have accepted the changes in any revised Cookie Policy by your continued use of the Site after the date such revised Cookie Policy is posted.</p><p>This Cookie Policy was generated by <span>Termly's Cookie Consent Manager</span>.</p><p><strong>USE OF COOKIES</strong></p><p>A 'cookie' is a string of information which assigns you a unique identifier that we store on your computer. Your browser then provides that unique identifier to use each time you submit a query to the Site. We use cookies on the Site to, among other things, keep track of services you have used, record registration information, record your user preferences, keep you logged into the Site, facilitate purchase procedures, and track the pages you visit. Cookies help us understand how the Site is being used and improve your user experience.</p><p><strong>TYPES OF COOKIES</strong></p><p>The following types of cookies may be used when you visit the Site:</p><p><strong>Advertising Cookies</strong></p><p>Advertising cookies are placed on your computer by advertisers and ad servers in order to display advertisements that are most likely to be of interest to you. These cookies allow advertisers and ad servers to gather information about your visits to the Site and other websites, alternate the ads sent to a specific computer, and track how often an ad has been viewed and by whom. These cookies are linked to a computer and do not gather any personal information about you.</p><p><strong>Analytics Cookies</strong></p><p>Analytics cookies monitor how users reached the Site, and how they interact with and move around once on the Site. These cookies let us know what features on the Site are working the best and what features on the Site can be improved.</p><p><strong>Our Cookies</strong></p><p>Our cookies are 'first-party cookies', and can be either permanent or temporary. These are necessary cookies, without which the Site won't work properly or be able to provide certain features and functionalities. Some of these may be manually disabled in your browser, but may affect the functionality of the Site.</p><p><strong>Personalization Cookies</strong></p><p>Personalization cookies are used to recognize repeat visitors to the Site. We use these cookies to record your browsing history, the pages you have visited, and your settings and preferences each time you visit the Site.</p><p><strong>Security Cookies</strong></p><p>Security cookies help identify and prevent security risks. We use these cookies to authenticate users and protect user data from unauthorized parties.</p><p><strong>Site Management Cookies</strong></p><p>Site management cookies are used to maintain your identity or session on the Site so that you are not logged off unexpectedly, and any information you enter is retained from page to page. These cookies cannot be turned off individually, but you can disable all cookies in your browser.</p><p><strong>Third-Party Cookies</strong></p><p>Third-party cookies may be place on your computer when you visit the Site by companies that run certain services we offer. These cookies allow the third parties to gather and track certain information about you. These cookies can be manually disabled in your browser.</p><p><span><strong>[Other]</strong></span></p><p><strong>CONTROL OF COOKIES</strong></p><p>Most browsers are set to accept cookies by default. However, you can remove or reject cookies in your browser's settings. Please be aware that such action could affect the availability and functionality of the Site.</p><p>For more information on how to control cookies, check your browser or device's settings for how you can control or reject cookies, or visit the following links:</p><p>In addition, you may opt-out of some third-party cookies through the Network Advertising Initiative's Opt-Out Tool.</p><p><strong>OTHER TRACKING TECHNOLOGIES</strong></p><p>In addition to cookies, we may use web beacons, pixel tags, and other tracking technologies on the Site to help customize the Site and improve your experience. A 'web beacon' or 'pixel tag' is tiny object or image embedded in a web page or email. They are used to track the number of users who have visited particular pages and viewed emails, and acquire other statistical data. They collect only a limited set of data, such as a cookie number, time and date of page or email view, and a description of the page or email on which they reside. Web beacons and pixel tags cannot be declined. However, you can limit their use by controlling the cookies that interact with them.</p><p><strong>PRIVACY POLICY</strong></p><p>For more information about how we use information collected by cookies and other tracking technologies, please refer to our Privacy Policy <span>[CLICK HERE]</span>/posted on the Site. This Cookie Policy is part of and is incorporated into our Privacy Policy. By using the Site, you agree to be bound by this Cookie Policy and our Privacy Policy.</p><p><strong>CONTACT US</strong></p><p><span>If you have questions or comments about this Cookie Policy, please contact us at:</span></p><p><span>[Company Name]</span></p><p><span>[Street Address]</span></p><p><span>[City, State Zip]</span></p><p><span>[Phone Number]</span></p><p><span>[Fax Number]</span></p><p><span>[Email] </span></p><br><br><br><br>

broken image