Have you ever wondered what those tiny data bits stored in your browser are all about? Maybe you noticed a pop-up about cookies on your favorite website or have been curious when a friend mentioned they “store data” in your browser. In this article, I’ll explain everything you need to know about web cookies in plain language. We’ll cover everything from their definition and structure to how to manage them with JavaScript. By the end, you’ll have a thorough understanding of how cookies work, why they are used, and the different types you might encounter while surfing the web.
This article is structured as follows:
- What are Web Cookies?
- How a Cookie Looks Like
- Managing Cookies with JavaScript
- Who Really Writes Cookies?
- Use Cases for Cookies
What are Web Cookies?
At its core, a web cookie is a small piece of data that a website stores on your computer or device when you visit. Think of cookies as a friendly reminder that helps the website recognize you on your next visit. They can store various bits of information—like your login status, preferences, or even items in your shopping cart.
Imagine walking into your favorite coffee shop. The barista remembers your order from the last time you visited, so they ask if you’d like the same latte you had before. Cookies work in a similar way; they “remember” your previous interactions with a website so that it can provide a smoother, more personalized experience.
Here are some key points about web cookies:
- Small and Simple: Cookies are tiny text files containing bits of data. They are not meant for large amounts of information but rather for small pieces of information that make your browsing experience easier.
- Temporary or Long-lasting: Some cookies disappear when you close your browser, while others stick around for longer, keeping your information even after you shut down your device.
- Site-specific: Cookies are associated with the website that created them. This means that one website’s cookies can’t be read by another, ensuring a level of privacy between different sites.
This basic functionality is crucial for many features you take for granted on the web. Without cookies, websites would have a hard time knowing if you’re already logged in, what language you prefer, or what products you looked at during your last visit.
How a Cookie Looks Like
Now that we’ve defined what a cookie is, let’s get a bit more technical.
A cookie is represented by a key-value pair, where the key is the name of the cookie, and the value is the data associated with it. Cookies also have attributes such as expiration date, domain name, and path, which can be used to provide additional control over how the cookie is used and accessed.
Let’s look at each of these attributes of a Cookie in detail
Attribute | Description |
---|---|
Name | A label for the cookie. For instance, a website might have a cookie called sessionID . |
Value | The data associated with the cookie. Using the example above, sessionID might be set to a unique string like abc123xyz . |
Domain | The website that can access the cookie. This ensures that only the site that created the cookie can read it. |
Path | Specifies which part of the website the cookie applies to. Often, this is set to / , meaning the entire website. |
Expiration Date | Cookies can have an expiration time. Some cookies are temporary and disappear when you close your browser (called session cookies), while others have a specific expiry date, after which they are automatically removed. |
Security Flags | dditional flags can be set for enhanced security. For example, a cookie might be marked as “secure” (only sent over HTTPS connections) or “HttpOnly” (inaccessible via JavaScript). |
Picture this: When you log into your favorite online store, your browser might receive a cookie that looks like this in its raw form:
Name: userToken
Value: 5f2d3g4h5i
Domain: www.example.com
Path: /
Expires: Wed, 09 Jun 2025 10:18:14 GMT
Secure: Yes
HttpOnly: Yes
This simple structure is all it takes to store a small amount of data that can be retrieved on your next visit, helping the website keep track of who you are.
Managing Cookies with JavaScript
JavaScript is the programming language of the web, and it plays a vital role in handling cookies on the client side. If you’re a developer or just curious about how things work behind the scenes, understanding how to create, read and remove cookies using JavaScript is essential.
Adding Cookies
Creating (or adding) a cookie in JavaScript is as simple as assigning a string to document.cookie
. Here’s a basic example:
document.cookie = "username=JohnDoe; path=/; expires=Fri, 31 Dec 9999 23:59:59 GMT";
If you omit the expires
attribute (and max-age
as well), the cookie becomes a session cookie and will vanish as soon as you close your browser.
You can set multiple cookies simply by writing multiple assignments, though it’s usually more organized to build a small function to handle cookie creation:
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
let expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
Now you can do:
setCookie('favoriteColor', 'blue', 30);
That will store a cookie named favoriteColor
with the value blue
for 30 days.
Reading Cookies
Reading cookies with JavaScript might seem a bit mysterious at first, but it’s actually quite straightforward.
The browser stores cookies in a string called document.cookie
. This string contains all the cookies available to the current page, separated by semicolons.
For example, let’s say you want to check which cookies are available. You can simply open your browser’s developer console and type:
console.log(document.cookie);
This might return something like:
"userToken=5f2d3g4h5i; theme=dark; sessionID=abc123xyz"
From here, you can split the string and parse it to extract specific cookie values. A common approach is to write a small function that looks for a cookie by name:
function getCookie(cookieName) {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.startsWith(cookieName + '=')) {
return cookie.substring(cookieName.length + 1);
}
}
return null; // Return null if the cookie is not found
}
By using this function, you can easily read any cookie that your site has set.
Removing Cookies
There might be times when you need to delete a cookie—perhaps you’re logging out of a website or you just want to clear outdated data. Removing a cookie is almost as simple as setting it, with one small twist: you set its expiration date to a time in the past.
Here’s how you might remove a cookie using JavaScript:
function deleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
}
When you call this function with the name of the cookie you want to remove, the browser sees the expiration date as having already passed and then deletes the cookie accordingly.
This method works well for most scenarios, but keep in mind that if the cookie was set with specific flags (such as Secure
or HttpOnly
), you might need to ensure that your removal command adheres to those constraints.
Who Really Writes Cookies?
The phrase “Who writes cookies?” might seem a little odd at first glance, but it’s an important aspect to understand. In the world of web development, cookies are written by the server and the client-side code (usually JavaScript). Let’s understand roles:
The Server
When you visit a website, the server (the computer that hosts the website) can send a cookie to your browser as part of the HTTP response headers. For example, when you log in, the server might create a cookie to keep track of your session:
Set-Cookie: sessionID=abc123xyz; Expires=Wed, 09 Jun 2025 10:18:14 GMT; Path=/; Secure; HttpOnly
This header tells your browser to store a cookie named sessionID
with a value of abc123xyz
and various attributes.
This server-generated cookie is often used to maintain a user session or remember user-specific data.
The Client
In addition to server-side operations, client-side code (usually JavaScript) can also write cookies. This is particularly useful for personalization or tracking user preferences without having to interact with the server every time. For example, a website might allow you to choose a theme (like dark mode or light mode), and JavaScript can store this preference in a cookie:
document.cookie = "theme=dark; path=/; expires=Fri, 31 Dec 2025 23:59:59 GMT";
Here, the client (your browser) is directly managing the cookie, giving the site an immediate way to remember your settings.
In both cases, the code—whether executed on the server or the client—determines the cookie’s properties and how it’s used. This duality is what makes cookies flexible and powerful for creating personalized and efficient web experiences.
Use Cases for Cookies
Cookies are incredibly versatile, and there are several different types, each designed for a specific purpose. Let’s explore the main categories of cookies you’re likely to encounter:
Session Cookies
These are temporary cookies stored in memory and are deleted as soon as the user closes the browser. This type of cookie does not have an expiration date.
These cookies typically store information like the pages you clicked on or items you temporarily saved in your cart. They’re primarily used so that the website can recall what you’re doing while moving from page to page. If you’ve ever shopped online and suddenly found that your cart is empty after clicking to a new section, there might be an issue with session cookies. Ideally, they help the site “remember” that you have items in your cart.
Imagine you’re buying concert tickets on a ticketing website. You find two great seats, click “Add to Cart,” and then move to a different section of the site to check out upcoming shows by the same artist. The session cookie keeps track of your selected seats so that when you come back, you can proceed to checkout without having to select your seats all over again. Once you close your browser or the session times out, those cookies vanish, and you would need to start the selection process again next time.
Persistent Cookies
Unlike session cookies, persistent cookies stick around even after you close your browser. They might not last forever, but they do have a set expiration date that can be days, months, or even years in the future.
This type of cookie is used for features that benefit from being remembered over a longer period. For instance, if you have a favorite language preference on a global website or if you’ve chosen a particular theme on a news site, the persistent cookie will ensure that the site “remembers” you the next time you log in or even just open the site. It’s also what keeps you logged in on many social media platforms, so you don’t have to type your username and password every single time you want to check your notifications.
Think about when you open Netflix, and it automatically shows you the last episode you watched, recommends new shows, and keeps track of your preferred language. All of that information doesn’t just vanish once you close Netflix. A persistent cookie helps store your preferences and your account details, so you can pick up right where you left off the next time you log in—without having to remind Netflix who you are each time.
First-Party Cookies
First-party cookies come directly from the website you’re visiting and are generally considered the “good guys” of the cookie world, at least compared to some others. These cookies are designed to enhance your experience with the site you’re on, such as remembering items in your cart, keeping you logged in, or storing your language preferences. Because they originate from the site’s own servers, they’re often seen as less intrusive. They’re also typically used to generate analytics about how people navigate the site, which helps site owners improve layouts and content.
Suppose you frequently visit a blog about healthy cooking. The site has a special area just for members, where you can see premium recipes. When you log in, the blog sets a first-party cookie to remember your login details. As you browse recipe after recipe, you don’t have to sign in again each time you read a new article. The cookie also helps the site keep track of which recipes you’ve viewed so that it can recommend new ones you haven’t tried yet.
Third-Party Cookies
Third-party cookies are where things get a little more complicated. These cookies aren’t set by the website you’re directly visiting, but rather by a separate domain—usually an advertiser or analytics service. You’ve probably noticed that when you browse around online looking at sneakers or a new phone, you start seeing ads for those exact products on totally different websites. This is likely because a third-party cookie was placed on your browser to track your interests.
These cookies can be useful in many ways—like helping to measure how effective an ad campaign is—but they also have a reputation for being intrusive. They follow your online activity across different sites, which is why many people see them as a privacy concern. It’s almost like you’re window shopping at the mall, and there’s a salesperson following you from store to store, taking notes on what you like, so they can pitch you products later.
You’re reading a travel blog about the best destinations in Europe, and there’s a banner ad from a travel agency offering deals on flights. That banner ad is likely pulled from an ad network, which sets a third-party cookie in your browser. Later, when you visit a totally unrelated news site, you notice ads for flight deals again. That’s because the third-party cookie from the ad network “remembered” that you were looking at European travel information and decided to show you similar offers.
Same Site Cookies
Same-site cookies are a bit more specific. They’re designed to work only with the same domain and not be shared across different sites, which helps provide a layer of protection against some forms of cross-site request forgery (CSRF) attacks.
This approach helps maintain more control over how cookies are used and who can access them. It’s especially relevant for websites that deal with sensitive data, such as online banking portals and healthcare websites, because it reduces the risk of an outside site hijacking the user’s session. It’s a good security measure for websites that want to keep user interactions strictly contained within their own domain.
Consider a web-based email service, like a smaller specialized email platform you might use for work. They employ same-site cookies to ensure that once you log in, your browser won’t leak that authentication data to another domain, even if there’s a link or script embedded from somewhere else. This means if you’re reading an email and click an embedded link to an external site, that external site can’t access your email login cookie. This lowers the risk of someone sneaking into your session.
Secure Cookies
Secure cookies, as their name suggests, are only sent over secure channels—namely HTTPS. This ensures that the data in the cookie is encrypted as it travels between your browser and the website’s server. If someone tries to intercept the communication, all they’ll see is garbled information rather than something that looks like your username or other sensitive data.
Many websites that handle sensitive information, like online banking or medical records, will use secure cookies. It’s a must-have if you want to protect people’s personal data and ensure that cybercriminals can’t just swoop in and grab unencrypted info as it travels from point A to point B. In other words, if you see that a website is using HTTPS (you’ll notice a little lock icon in your browser’s address bar), that’s your cue that any secure cookies from that domain are likely encrypted in transit.
When you log into your online banking account, the site may set a secure cookie that includes a form of session identification. Because it’s secure, if someone tries to eavesdrop on the network traffic, all they’ll see is encrypted data. They won’t be able to read your account details or session IDs, keeping your financial information and transactions much safer as you move money around or pay bills online.