One way or another, 4.66 billion people actively use the internet and interact with HTTP cookies every day. In many ways, HTTP cookies provide you with a streamlined and personalized website experience, and for some, these services are often overlooked or misunderstood.
Aside from the user end, HTTP cookies allow web developers to create more personalized and convenient website visits for their users. Aside from the benefits that HTTP cookies offer, there are security concerns also to consider. More commonly discussed in the past couple of years, many individuals concern themselves with personal information privacy and security.
No matter your background knowledge on HTTP cookies, we hope to provide a comprehensive post on how HTTP cookies work. Here’s what we’ll cover today:
Get hands-on with Web Application Security for free Learn the fundamentals of Web Application Security with Educative’s 1-week free trial.Web Application Security: Understanding HTTP Security Headers
Cookies are small pieces of data used as a storage medium in the browser and sent to the server with each request. They are helpful for session management, user personalization, and tracking.
Session management:
Session management facilitates secure interactions between the user and some service or application. As the user continues to interact with the web application, they submit requests that help track the user’s status during the session.
Examples: Logins, auto-filled form fields, shopping lists
User personalization:
User personalization retains user preferences and settings for reapplication upon user login or application start. Settings are saved and synchronized with a central database to help users return to preferred settings used during their first application interaction.
Examples: User preferences, themes, language
Tracking:
Tracking records and analyzes users’ web browsing habits and finds the number and type of pages the user visits. Details include time spent on page and page sequence across a user’s sessions. Due to the sensitive information behind tracking, users should be aware of vulnerabilities from visiting insecure web pages.
Example: Ad tracking
There are two ways to create HTTP cookies. Whether through Google Chrome or Mozilla Firefox, you can type in Javascript code to set the cookie into the console with any browser you access. The other option involves the web server sending one or more set-cookie headers.
1. Client-side
After opening the console, you can set a cookie with JavaScript by typing out the code:
document.cookie="example=1"
In order to check if your cookie is set up, open up the “Application” tab and click the “Cookies” tab to access your new cookie. Here’s a picture to show what you should see:
2. Web server-side
In the case where you wish to build your own website, you can create a HTML script where a button creates a cookie.
<<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-compatible" content ="ie=edge"><title>Document</title></head><body><button id = 'btnCreateCookie'>Create Cookie </button><script>const btnCreateCookie = document.getElementbyID("btnCreateCookie")btnCreateCookie.addEventLister("click", e=> document.cookie = "example-3")</script></body></html>
Once you have the HTML file ready, you can create an index.js application that will return the HTML file using an Express application for Node.js.
const app = require("express")()app.get("/", (req, res) => {res.sendFile(`${__dirname}/index.html`)})app.listen(8080, ()=>console.log("listening on port8080"))
const app = require("express")()app.get("/", (req, res) => {res.setHeader("set-cookie", ["setfromserver=1"])res.sendFile(`${__dirname}/index.html`)})app.listen(8080, ()=>console.log("listening on port8080"))
By having the browser set the cookie, you won’t have to manually type in JavaScript to create a cookie for each visitor.
No matter the type of cookie, cookie properties remain consistent across all cookie types. The cookie properties you should take note of include:
Cookie scope
The scope of a cookie determines what URLs cookies should be sent to. The scope of a cookie splits into two different attributes:
Domain
More simply put, domains attributes are “buckets” in which cookies are placed. Each cookie assigns itself to a unique domain name, which helps keep cookies organized and specific to the pages users enter.
Here’s an example:
Domain=example.io will set cookies to be available for on all subdomains such as developer.example.io
Path
The path attribute indicates a specific URL path to send the cookie header. In order to set cookies for different paths, you can write the code:
document.cookie="examplepath1=1; path=/path"
document.cookie="examplepath2=2; path=/blog"
Now, when you enter a website via any URL with /path, such as https://www.example.io/path/, you will send a cookie header "educativepath1=1".
Just as another example, if you were to enter a website via any URL with /blog, such as https://www.example.io/blog
You will send a cookie header "educativepath2=2".
Other requested paths such as:
/bloglearn
/pathlearn
/learnpath
will not send a cookie header unless a path attribute is set up for these URLs.
Expires and Max-age
Another property to consider is the lifetime of a cookie or, more simply, the cookie’s expiration date. The Expires and Max-Age attributes fall under a persistent cookies category. Despite the name “permanent cookie,” the Expires attribute will delete a cookie at a specified date. In contrast, the Max-Age attribute will delete a cookie after a specified period of time.
On the other hand, session cookies are deleted when the current session ends. Keep in mind that some browsers define when that current session ends, which can be an indefinite amount of time.
SameSite
We covered earlier how HTTP cookies are set for direct URLs, but what about clicking a link within that direct URL? When clicking a link within a page, your cookies can be sent from the new page you are directed to. This is where the SameSite attribute comes into play. Put simply, Samesite specifies whether cookies are sent with cross-site requests or whenever you click a link on any given page. For example, let’s follow this sequence for how cookies are sent and received when navigating between one web page to another.
You type in the URL www.example.com
You will receive a first-party cookie
On www.example.com, you click a link or button that sends a Fetch request to www.cookie.com.
www.cookie.com sets a cookie with Domain=cookie.com
www.example.com now holds a third-party cookie from www.cookie.com.
A SameSite attribute specifies whether third-party cookies are sent with three values:
Strict
With a SameSite value of strict, cookies will only be sent through a first-party cookie context and not third-party cookies.
Lax
With a SameSite value of lax, cookies will only be sent when users actively click a link to a third-party website. If the SameSite attribute isn’t directly set, lax becomes the default value.
None
With a SameSite value of None, cookies will be sent in all contexts.
Give yourself an edge at your next interview
With Educative Unlimited, you can access hundreds of courses tailor-made for software developers for less than $17 a month. Stay on the cutting edge by taking interview prep courses designed by industry experts at top tech companies.Get started with a FREE 1-week trial today
Session cookies
Also known as temporary cookies, session cookies expire once you close or leave the browser. You’ll notice a website is using session cookies when you have to enter your login credentials every time you open the page.
One example to consider is the shopping cart on any eCommerce site. Session cookies help keep items in the shopping cart when you click an item to open a new tab. Without session cookies, the website would not remember the items you clicked on previously.
First-Party cookies
First-party cookies are stored directly on your computer by the website you are visiting. The website collects analytics and helpful information to improve your user experience.
One use case to consider is the example given earlier in this blog post. When accessing a website such as www.example.com, the website will send a request to your computer that provides a unique cookie value under the domain www.example.com. Without first-party cookies, websites won’t automatically log you in or remember your preferences from past sessions.
Third-Party cookies
Third-party cookies are created by domains other than the one you directly access. Generally used for tracking purposes, third-party cookies are stored even after the browser is closed. One common use case involves ad tracking from websites other than the ones you visit. For example, when browsing through various product pages on an eCommerce website, you might be exposed to third-party cookies from a domain outside of the specific website you visited. Later on, when you close your browser, a third-party cookie can be used to track whether or not you bought the product you saw on the website.
Specific pictures pulled from a third-party website outside the particular domain you are on can contain third-party cookies that give other domains the ability to send targeted emails or ads for an item you looked at but didn’t purchase.
Secure cookies
Secure cookies prevent unauthorized parties from observing cookies sent to a new user within an HTTP response. With the Secure attribute, HTTP requests will only include the cookie if transmitted over a secure channel.
HttpOnly cookies Initially implemented by Microsoft Internet Explorer developers in 2002, HttpOnly flags can be included in a Set-Cookie HTTP header. The HttpOnly attribute mitigates the risk of users accidentally accessing a link that may exploit a cross-site scripting flaw.
Cross-site scripting attacks are malicious scripts added to a trusted website that gives attackers access to cookies and other sensitive information.
Zombie cookies
Somewhat indicated by the name, zombie cookies are cookies that come back to life even when deleted or the browser is closed. Zombie cookies store themselves in places outside of the web browser’s dedicated cookie storage. When the user destroys a cookie, a zombie cookie can take the replica stored elsewhere and attach it to the user’s cookie storage again.
Historically, ad companies such as Quantcast were sued for using zombie cookies to track users and store personal information. States like California deem the use of zombie cookies as an illegal invasion of privacy.
When working with HTTP cookies, it’s crucial to understand how browsers enforce limits and eviction policies.
Typically, a cookie value (plus name, attributes) must stay under ~4 KB (4096 bytes) per cookie. Exceeding that may truncate or drop the cookie. Browsers also impose a maximum number of cookies per domain (commonly ~20–50). When limits are hit, older cookies may be evicted.
These constraints mean cookies are best used for small tokens or identifiers, not large payloads. Anything larger (user profiles, lists) should live in server-side storage or other browser storage.
Persistent cookies with Expires or Max-Age survive beyond browser closes, but browsers may purge them if unused for long periods. Some frameworks implement sliding expiration—resetting the cookie’s expiration on each request to maintain active sessions.
Session cookies (no expiry) are cleared when the browser process terminates or sometimes when a browser instance is closed. Note: mobile browsers may suspend sessions differently, so session reliability can vary.
Over time, browsers have tightened rules around cookies to combat tracking. These changes affect how cookies work in practice.
Modern browsers now default cookies to SameSite=Lax if no attribute is set. That means cookies will not be sent in many cross-site contexts (e.g., AJAX or image loads), reducing implicit third-party tracking. If you intend cross-site cookie use, you must explicitly set SameSite=None; Secure.
Some browsers or proposals introduce cookie partitioning (or "Partitioned Storage") so that third-party cookies are scoped per top-level domain. This prevents cross-site trackers from sharing cookie stores across unrelated sites. For example, embedding content from domain A on domain B gets a separate cookie store for that embedding context.
To allow cross-site cookies when user consents, browser APIs are emerging (e.g. Storage Access API) where embedded frames can request access. Until granted, cookies are blocked or restricted. This means your cookie logic in embedded contexts may be blocked unless user interaction allows it.
Cookies are just one of several browser storage mechanisms. Understanding alternatives helps choose what fits best.
Storage | Scope | Lifetime | JS Accessible | Use Cases |
Cookies | Sent on HTTP requests | Persistent or session | Yes (unless HttpOnly) | Authentication tokens, small state |
localStorage | Per origin | Persistent until cleared | Yes | Client-side preferences, caching |
sessionStorage | Per tab/window | Until tab close | Yes | Per-session UI state |
IndexedDB | Per origin | Persistent | Yes | Structured data, large storage |
When to use cookies vs others:
Use cookies when server needs to read the data (auth tokens, CSRF tokens).
Use client-only storage (localStorage, IndexedDB) for large data or user settings not needed server-side.
Always avoid storing sensitive secrets in client storage unless encrypted.
To wrap up your deeper coverage, here’s a practical checklist for better cookie usage.
Always enforce HTTPS + Secure flag and pair with SameSite=None only when necessary.
Use HttpOnly to prevent script access.
Limit cookie size and avoid storing rich data inside cookies.
Use prefixes (__Secure-, __Host-) when possible to enforce stricter rules.
Regularly rotate cookie values (e.g. tokens) and invalidate old ones.
Use sliding expiration to keep sessions active only when users interact.
Be aware of browser cookie policy changes, and test in modern browsers.
For multi-domain apps, prefer server-side session storage with short cookie identifiers.
Respect user privacy, avoid excessive tracking, and comply with policy requirements (e.g. consent, GDPR).
Congrats on taking your first steps with HTTP cookies! HTTP cookies have been around for a long time and hold many opportunities to improve user experience and authentication.
While we covered the basics of HTTP cookies, there’s still so much more to learn about HTTP cookie security, such as:
HTTP Security Headers
X XSS Protection
Testing for Security Headers To learn these concepts and more, check out Educative’s course Web Application Security: Understanding HTTP Security Headers. In this hands-on course, you’ll cover topics ranging from HTTP Strict Transport Security, the state of HTTP security, and more. By the end, you’ll have learned how to increase security using web controls such as HTTP headers and ensure that you’re up to date with security controls. Happy learning!