If you’re a JavaScript developer and you want to learn about browser cookies and what you can do with them, you’re at the right place. This article will cover how browser cookies work, how you can access and manipulate them both from the client and server, and how to control their visibility across browsers using their attributes. Show
What are cookies and how do they work?A browser cookie is a small piece of data stored on a browser that’s created either by the client-side JavaScript or a server during an HTTP request. The browser can then send that cookie back with requests to the same server and/or let the client-side JavaScript of the webpage access the cookie when a user revisits the page. Cookies are generally used for session management, personalization (such as themes or similar settings), and tracking user behavior across websites. There was a time when cookies were used for all kinds of client-side storage, but there was an issue with this approach. Since all domain cookies are sent with every request to the server on that domain, they can significantly affect performance, especially with low-bandwidth mobile data connections. For the same reason, browsers also typically set limits for cookie size and the number of cookies allowed for a particular domain (typically 4kb and 20 cookies per domain). With the modern web, we got the new
Web Storage APIs ( So, if you want to persist data only on the client-side, it’s better to use the APIs because they are more intuitive and easier to use than cookies and can store more data (usually up to 5MB). Setting and accessing cookiesYou can set and access cookies both via the server and the client. Cookies also have various attributes that decide where and how they can be accessed and modified. But, first, let’s look at how you can access and manipulate cookies on the client and server. Client (browser)The JavaScript that downloads and executes on a browser whenever you visit a website is generally called the client-side JavaScript. It can access cookies via the This means you can read all
the cookies that are accessible at the current location with const allCookies = document.cookie; // The value of allCookies would be something like // "cookie1=value1; cookie2=value2" Similarly, to set a cookie, we must set the value of document.cookie = "hello=world; domain=example.com; Secure"; // Sets a cookie with key as hello and value as world, with // two attributes SameSite and Secure (We will be discussing these // attributes in the next section) Just so you’re not confused, the above statement does not override any existing cookies; it just creates a new one or updates the value of an existing one if a cookie with the same name already exists. Now, I know this is not the cleanest API you have ever seen. That’s why I recommend using a wrapper or a library like js-cookie to handle client cookies: Cookies.set('hello', 'world', { domain: 'example.com', secure: true }); Cookies.get('hello'); // -> world Not only does it provide a clean API for CRUD operations on cookies, it also supports TypeScript, helping you avoid any spelling mistakes with the attributes. ServerThe server can access and modify cookies via an HTTP request’s response and request headers. Whenever the browser sends an HTTP request to the server, it attaches all the relevant cookies to that site with the Check the request headers of almost any web app you use, and you’ll find the cookies sent to the server with request headers as a semicolon-separated string. Cookies being sent to the server with request headersYou can then read these cookies on the server from the request headers. For example, if you use
Node.js on the server, you can read the cookies from the request object, like the snippet below, and get the semicolon-separated http.createServer(function (request, response) { var cookies = request.headers.cookie; // "cookie1=value1; cookie2=value2" ... }).listen(8124); Similarly, to set a cookie, you can add a response.writeHead(200, { 'Set-Cookie': 'mycookie=test; domain=example.com; Secure' }); Also, chances are you won’t use plain Node.js; instead, you can use it with a web framework like Express.js. Accessing and modifying cookies gets much easier with Express by adding middleware. For reading, add var express = require('express') var cookieParser = require('cookie-parser') var app = express() app.use(cookieParser()) app.get('/', function (req, res) { console.log('Cookies: ', req.cookies) // Cookies: { cookie1: 'value1', cookie2: 'value2' } res.cookie('name', 'tobi', { domain: 'example.com', secure: true }) }) app.listen(8080) And yes, all of this is supported with TypeScript, so there is no chance of typos on the server as well. JavaScript cookie attributesNow that you know how you can set and access cookies, let’s dive into the attributes of cookies. Apart from name and value, cookies have attributes that control a variety of aspects that include cookie security, cookie lifetime, and where and how they can be accessed in a browser. Domain attributeAccording to MDN, the So, when accessing a cookie using client-side JavaScript, only the cookies that have the same domain as the one in the URL bar are accessible. Similarly, only the cookies that share the same domain as the HTTP request’s domain are sent along with the request headers to the server. Remember that having this attribute doesn’t mean you can set cookies for any domain because that would obviously be a huge security risk. (Imagine an attacker on evil.com modifying the cookies for your site, awesome.com, when the user visits their website.) More great articles from LogRocket:
So, the only reason this attribute exists is to make the domain less restrictive and make the cookie accessible on subdomains. For example, if your current domain is But, you might want the same cookie
to be available on other subdomains as well. If this is the case, set However, this does not mean that you can set any domain value for cookies; top-level domains (TLDs) like Initially, browser vendors maintained lists of these public domains internally, which inevitably caused inconsistent behavior across browsers. To tackle this, the Mozilla Foundation started a project called the Public Suffix List that records all public domains and shares them across vendors. This list also includes services like Path attributeThe Expires attributeThe And guess what? It also removes cookies by setting the Secure attributeA cookie with
the Unless you are serving your websites via an unsecured HTTP connection (which you shouldn’t) you should always use this attribute with all your cookies. HttpOnly attributeThis attribute, as the name probably suggests, allows cookies to be only accessible via the server. So, only the server can set them via the response headers. If they are sent to the server with every subsequent request’s headers, they won’t be accessible via client-side JavaScript. HTTPOnly attribute exampleThis can partially help secure cookies with sensitive information, like authentication tokens, from XSS attacks since any client-side script can’t read the cookies. But, remember it does not guarantee complete security from XSS attacks. This is because if the attacker can execute
third-party scripts on your website, they might not be able to access the cookies, and instead, can directly execute any relevant API requests to your server , causing the browser to readily attach your secure Imagine one of your users visits a page where a hacker injected their malicious script into your website. They can execute any API with that script and act on the user’s behalf without them ever knowing. So, when people say that
SameSite attributeAt the beginning of this article, we saw how cookies for a particular domain are sent with every request to the server for the corresponding domain. This means that if your user visits a third-party site, and that site makes a request to APIs on your domain, then all the cookies for your domain will be sent with that request to your server. This can be both a boon and a curse depending on your use case. This can be a boon in the case of something like YouTube embedding. For example, if a user who is logged in to YouTube on their browser visits a third-party website containing YouTube embeds, they can click on the Watch Later button on the embedded video and add it to their library without leaving the current website. This works because the browser sends the relevant cookies for YouTube to the server confirming their authentication status. These types of cookies are also called third-party cookies. The curse this can cause is in basically any other use case you didn’t intend it to happen. For instance, if a user visits a malicious website where that website makes a request to your server, and if the server doesn’t validate the request properly, then the attacker can take actions on the user’s behalf without their knowledge. This is basically a CSRF attack. To help prevent this type of attack,
the IETF proposed in 2016 a new attribute in cookies called This means you should only attach cookies to the request when the domain in your URL bar matches the cookie’s domain. SameSite attribute with StrictThere are three types of values you can set for the When set to The This is helpful in cases when a user clicks on your website from a Google search result or is redirected via a shortened URL. Then You can learn more about Privacy and third-party cookiesWe briefly explained third-party cookies in the previous section. In short, any cookie set by a site other than the one you are currently on is a third-party cookie. You may have also heard about how infamous third-party cookies are for tracking you across websites and showing personalized ads. Now that you know the rules of cookies, you can probably guess how they might do it. Basically, whenever a website uses a script or adds an embedded object via IFrame for third-party services, that third-party service can set a cookie for that service’s domain with HTTP response headers. These cookies can also track you across websites that use the same third-party service embeds. And finally, the data collected by these third-party services by identifying you via cookies can then show you personalized ads. To tackle this, many browsers like Firefox started blocking popular third-party tracking cookies via a new feature they call enhanced tracking protection (ETP). Although this protects users from the 3000 most common identified trackers, its protection relies on the complete and up-to-date list. Browsers are currently planning to eventually get rid of third-party cookies. Firefox is implementing state partitioning, which will result in every third-party cookie having a separate container for every website. Now, you might think that something like state partitioning will also break legitimate use cases for third-party cookies apart from tracking, and you’re right. So, browsers are working on a new API called Storage Access This API allows third-party context to request first-party storage access via asking users permission, which gives the service unpartitioned access to its first-party state. You can read about how it works in more detail on Mozilla’s blog. ConclusionI hope this article helped you learn something new about JavaScript cookies and gave you a brief overview of how they work, how they can be accessed and modified from the server and the client, and lastly, how the different attributes of cookies let you control their visibility and lifespan in the browser. LogRocket: Debug JavaScript errors more easily by understanding the contextDebugging code is always a tedious task. But the more you understand your errors the easier it is to fix them. LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to find out exactly what the user did that led to an error. LogRocket records console logs, page load times, stacktraces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier! Try it for free. How do I access cookies?Change your cookie settings. On your computer, open Chrome .. At the top right, click More Settings .. Under "Privacy and security," click Cookies and other site data.. Select an option: Allow all cookies. Block all cookies (not recommended). Block third party cookies in Incognito. Block third-party cookies.. Can you access cookie using JavaScript True or false?Yes! JavaScript can also manipulate cookies using the cookie property of the Document object.
How do I get a cookie by name in JavaScript?cookie property.. Syntax. document. ... . Example. document.cookie = "username=jai;. Geta cookie by name in javascript. function getCookie(cookieName) { let cookie = {}; document.cookie.split(';').forEach(function(el) { let [key,value] = el.split('='); cookie[key.trim()] = value; }) return cookie[cookieName]; }. Related topics:. How do you parse cookies in JavaScript?How to parse cookies in javascript?. separate each key-value pair using String.prototype.split(';'). Use Array. prototype. map() and String. prototype. split('=') to separate keys from values in each pair.. Use Array. prototype. reduce() and decodeURIComponent() to create an object with all key-value pairs.. |