This repository has been archived by the owner. It is now read-only. Show
Permalink Cannot retrieve contributors at this time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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 One of the most widespread use cases is authentication:
We can also access cookies from the browser, using There are many tricky things about cookies and their options. In this chapter we’ll cover them in detail. Reading from document.cookieDoes your browser store any cookies from this site? Let’s see:
The value of To find a particular cookie, we can split 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.cookieWe can write to A write operation to For instance, this call sets a cookie with the name
If you run it, then probably you’ll see multiple cookies. That’s because the
Technically, name and value can have any characters. To keep the valid formatting, they should be escaped using a built-in
Limitations There are few limitations:
Cookies have several options, many of them are important and should be set. The options are listed after
path
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 Usually, we should set domain
A domain defines where the cookie is accessible. In practice though, there are limitations. We can’t set any domain. There’s no way to let a cookie be accessible from another 2nd-level domain, so It’s a safety restriction, to allow us to store sensitive data in cookies that should be available only on one site. By default, a cookie is accessible only at the domain that set it. Please note, by
default a cookie is also not shared to a subdomain as well, such as
…But this can be changed. If we’d like to allow subdomains like For that to happen, when setting a cookie at For example:
For historical reasons, To summarize, the expires, max-ageBy 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
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
If we set
It’s an alternative to If set to zero or a negative value, the cookie is deleted:
secure
The cookie should be transferred only over HTTPS. By default, if we set a cookie at That is, cookies are domain-based, they do not distinguish between the protocols. With this
option, if a cookie is set by
samesiteThat’s another security attribute To understand how it works and when it’s useful, let’s take a look at XSRF attacks. XSRF attackImagine, you are logged into the site Now,
while browsing the web in another window, you accidentally come to another site The browser sends cookies every time you visit the site 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 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 optionThe cookie It has two possible values:
A cookie with In other words, whether a user follows a link from their mail or submits a form from If authentication cookies have the The protection is quite reliable. Only operations that come
from Although, there’s a small inconvenience. When a user follows a legitimate link to 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
data-changing operations with
A more relaxed approach that also protects from XSRF and doesn’t break the user experience. Lax mode, just like A
So, what But anything more complicated, like a network request from another site or a form submission, loses cookies. If that’s fine for you, then adding Overall, There’s a drawback:
So if we solely rely on But we surely can use httpOnlyThis option has nothing to do with JavaScript, but we have to mention it for completeness. The web-server uses the This option forbids
any JavaScript access to the cookie. We can’t see such a cookie or manipulate it using That’s used as a precaution measure, to protect from certain attacks when a hacker injects his own JavaScript code into a page and waits for a user to visit that page. That shouldn’t be possible at all, hackers should not be able to inject their code into our site, but there may be bugs that let them do it. Normally, if such a thing happens, and a user visits a web-page with hacker’s
JavaScript code, then that code executes and gains access to But if a cookie is Appendix: Cookie functionsHere’s a small set of functions to work with cookies, more convenient than a manual modification of There exist many cookie libraries for that, so these are for demo purposes. Fully working though. getCookie(name)The shortest way to access a cookie is to use a regular expression. The function
Here Please note that a cookie value is encoded, so setCookie(name, value, options)Sets the cookie’s
deleteCookie(name)To delete a cookie, we can call it with a negative expiration date:
Updating or deleting must use same path and domain Please note: when we update or delete a cookie, we should use exactly the same path and domain options as when we set it. Together: cookie.js. Appendix: Third-party cookiesA cookie is called “third-party” if it’s placed by a domain other than the page the user is visiting. For instance:
Third-party cookies are traditionally used for tracking and ads services, due to their nature. They are bound to the originating domain, so 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:
Please note: If we load a script from a third-party domain, like If a script sets a cookie, then no matter where the script came from – the cookie belongs to the domain of the current webpage. Appendix: GDPRThis topic is not related to JavaScript at all, just something to keep in mind when setting cookies. 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. Please note, that’s only about tracking/identifying/authorizing cookies. 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. But if we are going to set a cookie with an authentication session or a tracking id, then a user must allow that. Websites generally have two variants of following GDPR. You must have seen them both already in the web:
GDPR is not only about cookies, it’s about other privacy-related issues too, but that’s too much beyond our scope. Summary
Cookie options:
Additionally:
Can you read HttpOnly cookie in JavaScript?An HttpOnly cookie cannot be accessed by client-side APIs, such as JavaScript. This restriction eliminates the threat of cookie theft via cross-site scripting (XSS). If the browser allowed you to access it then it would be a defect in the browser.
How do I find HttpOnly cookies?Open dev tools by right clicking on page and then clicking on Inspect or Inspect Element. Click on Network tab. Click on any of the actual request and go to Headers section. Now look for set-cookie in response headers.
What is HttpOnly cookie JavaScript?If the HttpOnly flag is included in the HTTP response header, the cookie cannot be accessed through the client-side script. As a result, even if a cross-site scripting (XSS) flaw exists, and a user accidentally accesses a link that exploits the flaw, the browser will not reveal the cookie to the third-party.
How do you implement HttpOnly cookies?Implementation Procedure in Apache. Ensure you have mod_headers.so enabled in Apache HTTP server.. Add following entry in httpd.conf. Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure;SameSite=None.. Restart Apache HTTP server to test.. |