So, picture this: you’re at your favourite online store, browsing through the items. You pick a couple of things, add them to your cart and then, suddenly, you get distracted by a phone call. You return after an hour, and guess what? The items are still there in your cart, waiting for you. But how does the website remember your choices? The answer is through cookies!
In this post we will dive deep into what cookies are and explore how web applications use them to provide a seamless online experience. You’ll also get to inspect them firsthand in your own browser. Let’s get started!
What is a cookie
Cookies are tiny bits of data that websites store in your browser to remember things about you or your visit. Cookies were created out of a necessity for applications to remember things about users. You see, the HTTP protocol that the browser uses to communicate with web applications is stateless, meaning it doesn’t naturally remember anything from one request to another. It’s like having a conversation where you forget everything after each sentence: not very productive, right?
So, to make the internet more useful and interactive, cookies were invented. They allow websites to remember things about you and your behaviour, creating a more personalised and efficient online experience. They help remember your login information, shopping cart items, personal preferences, and more.
Why do cookies exist?
In the previous paragraph we touched on the idea that HTTP is stateless. To get an in-depth understanding of cookies, let’s dig deeper to understand why they were needed in the first place.
If you remember, in an earlier post we introduced the HTTP protocol as the “language” that your browser uses for any data exchange on the web. In that post, we mentioned HTTP is a stateless protocol. But what does “stateless” mean, and why does it matter?
In the world of computing, “state” refers to all the information a program has access to and can use to inform its operation at any given moment. In a “stateful” system, this information is remembered and used to inform future operations.
When we say HTTP is stateless, we mean that it doesn’t remember anything about previous requests and responses. Each transaction is processed independently, without any knowledge of the transactions that came before it. You can think of it like having a conversation with someone who has no memory of what was said a minute ago.
Now, while this statelessness helps to keep HTTP transactions simple and fast, it can be a bit of a problem when you need the web to remember certain things, like whether you’re logged in or what you have in a shopping cart. That’s where cookies come in. In 1994, Netscape’s development team introduced the concept of cookies as a way to circumvent the stateless nature of the HTTP protocol, that is, to remember information from one transaction to the next. Essentially, cookies allow us to create a sense of “memory” on the web.
The structure of a cookie
Now, onto the nitty-gritty. Cookies are small pieces of text, but they have a specific structure. For instance, these are the cookies Uphack stores, seen in the browser’s developer tools:
A cookie typically consists of:
- Name: The name of the cookie. It’s unique to the website that created the cookie.
- Value: The actual data that the cookie is storing. It could be a user ID, a session ID, or any other data that the site needs to store.
- Domain and Path: These determine which websites the cookie is valid for and what path on the website it’s valid for.
- Expiration Date: This determines how long the cookie will stay in your browser. Some cookies expire when you close your browser (session cookies), while others stay until their expiration date (persistent cookies), which could be days, months, or even years in the future.
- Secure, HttpOnly, and SameSite Flags: These are important security attributes. The Secure flag ensures the cookie is only sent over secure (HTTPS) connections. The HttpOnly flag prevents the cookie from being accessed through client-side scripts, helping to mitigate some types of cross-site scripting (XSS) attacks. The SameSite flag tells the browser if the cookie should be sent along with cross-site requests.
How cookies are set
At this point, you have a basic understanding of what cookies are and what their structure is. But you’re probably wondering…how do they get stored in your browser? What is the process that applications use to store cookies in your browser? Let’s find out.
Cookies can be set in two primary ways: either from the backend (server-side) or from the frontend (client-side) of an application. Let’s explore both methods.
The backend sets the cookie
When a web server responds to an HTTP request from a client (usually a web browser), it can include an HTTP header called Set-Cookie to instruct the browser to store a cookie. This might look something like:
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: username=JohnDoe
Upon receiving the response, the browser reads the Set-Cookie header and stores the cookie as instructed. For subsequent requests to the same domain, the browser automatically includes all stored cookies for that domain in the Cookie header.
The frontend sets the cookies
When building a web application, developers have the power to write JavaScript code that runs in the user’s browser. One of the APIs available for managing cookies is document.cookie. This API allows you to create, read, and delete cookies directly from the client-side script.
To set a cookie, developers typically include a line of code like this:
// Inside your web app's JavaScript code
document.cookie = "username=JohnDoe";
When a user navigates to the page that contains this code, their browser will be instructed to create or update a cookie with “username” as the cookie name and “JohnDoe” as the value. After storing the cookie, the browser will automatically include this cookie in the HTTP headers for every subsequent HTTP request to the same domain.
Note
When it comes to setting cookies on the client side, this isn’t typically something an end user can do on their own, unless they jump into the developer tools or execute JavaScript snippets in their browser. It’s usually the web developers who write client-side code to manage cookies.
Note
Setting cookies from the frontend is convenient, but it comes with limitations you should be aware of. Security: you can’t set the HttpOnly or Secure flags, which are essential for storing sensitive information securely. Reduced control: you don’t have the same level of control as you would server-side. For instance, you can’t explicitly set domain-wide or path-specific limitations.
How cookies are used
Think about it: without cookies, online shopping would be a nightmare. Every time you navigated away from the page, your cart would be empty. Or imagine having to log in every time you visit a new page on the same application. Not fun, right?
Cookies serve several key purposes:
- Session Management: They keep track of your activities during a particular session, such as maintaining your shopping cart items, or keeping you logged in as you navigate a website.
- Personalization: Cookies remember your preferences and settings, allowing websites to customize your experience. For instance, if you set your location on a weather website, a cookie will remember it for your next visit.
- Tracking: Cookies can track your behavior across websites, which can be used for targeted advertising. Have you ever wondered why you start seeing ads for shoes after searching for them online? That’s cookies at work!
The best way to get a feel for this is to look at the real thing. Open any site you use regularly, open your browser’s developer tools, and find the Cookies section under the Application or Storage tab. You will see the names, values, expiry dates and flags described above, set by the site you are on. Watch what changes when you log in, and what survives when you close the tab.
Conclusion
The takeaway is that cookies are a persistent storage mechanism that browsers use. They play an essential role in keeping users signed in, tracking their preferences, and managing other aspects of the user experience.
You now know what a cookie is made of, the two ways an application can set one, and how to read the cookies any site stores on you using the developer tools built into every major browser.
Cookies have a critical role in session management, and a security model of their own that browsers enforce. Both are worth a post each, and neither makes much sense without the fundamentals first. So let’s stick with the basics for now. Up next: what actually happens when you type a domain into your browser.