HTTP cookies: Complete 2026 guide
Learn how HTTP cookies power sessions, personalization, and web security. Build a real login flow, understand cookie vs localStorage trade-offs, and master modern browser behavior to design secure, scalable web applications.
HTTP cookies are small pieces of data stored in the browser and sent to the server with each request, enabling session management, user personalization, and tracking. They can be created client-side via JavaScript or server-side through Set-Cookie headers, and their behavior is governed by properties like Domain, Path, Expires, and SameSite.
Key takeaways
Cookie scope controls delivery: The Domain attribute determines which subdomains receive the cookie, while the Path attribute restricts it to specific URL paths.
SameSite defaults to Lax: Modern browsers automatically set SameSite=Lax when no value is specified, which blocks cookies from being sent in most cross-site requests like AJAX or image loads.
Cookie types serve different purposes: Session cookies expire when the browser closes, first-party cookies persist for login and preferences, and third-party cookies are primarily used for ad tracking across domains.
Security attributes matter: The Secure flag ensures cookies are only sent over HTTPS, and the HttpOnly flag prevents client-side JavaScript from accessing cookies to mitigate cross-site scripting attacks.
Size and storage limits apply: Each cookie must stay under approximately 4 KB, browsers cap cookies per domain at around 20 to 50, and larger data should be stored server-side or in localStorage and IndexedDB.
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
Introduction to HTTP cookies#
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
How to create HTTP cookies#
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.
Build a simple login session using HTTP cookies#
Understanding how cookies work is much easier when you see them in action. A great way to apply this knowledge is by building a simple login session system.
Imagine a basic web application where a user logs in with a username. Once authenticated, the server generates a session ID and sends it back to the browser as a cookie using the Set-Cookie header.
On subsequent requests, the browser automatically includes this cookie in the request headers. The server reads the session ID and uses it to identify the user, allowing them to stay logged in without re-entering credentials.
You can implement this using a simple Node.js server. After a successful login request, set a cookie with attributes like HttpOnly and Secure to protect it from client-side access and ensure it’s only sent over HTTPS.
Then, create a protected route that checks whether the cookie exists and corresponds to a valid session. If it does, the user is allowed access. If not, they are redirected to the login page.
This mini-project demonstrates one of the most important real-world uses of cookies: session management. It also highlights why security attributes like HttpOnly and SameSite are critical in production systems.
HTTP Cookie properties#
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
Cookie Types#
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 to use cookies vs localStorage or sessionStorage#
One of the most common questions developers ask is when to use cookies instead of other browser storage options.
Cookies are unique because they are automatically sent with every HTTP request. This makes them ideal for authentication, session tracking, and any data that the server needs to read.
In contrast, localStorage and sessionStorage are only accessible through JavaScript and are not included in HTTP requests. These storage options are better suited for client-side data like UI preferences, cached responses, or temporary state.
For example, if you need to store an authentication token that must be validated by the server on every request, cookies are the right choice. If you’re storing a user’s theme preference or UI state, localStorage is more efficient.
Understanding this distinction is critical in modern web development, as choosing the wrong storage mechanism can lead to performance issues or security vulnerabilities.
Cookie Limits, Size, Eviction & Behavior Over Time#
When working with HTTP cookies, it’s crucial to understand how browsers enforce limits and eviction policies.
Size and count constraints#
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.
Expiration, sliding sessions & idle timeouts#
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.
Privacy Trends, Browser Defaults & Partitioned Cookies#
Over time, browsers have tightened rules around cookies to combat tracking. These changes affect how cookies work in practice.
Browser-enforced SameSite defaults#
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.
Partitioned storage and isolation#
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.
Storage Access APIs & cookie blocking#
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.
Alternatives to Cookies & Choosing the Right Storage#
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.
Best Practices & Modern Guidelines for HTTP Cookies#
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).
Next steps: going deeper into web security and state management#
Now that you understand how HTTP cookies work, the next step is exploring how they fit into larger web security and application architecture.
Start by learning more about authentication systems, such as session-based authentication and token-based approaches like JWT. Understanding how cookies are used in these systems will give you a stronger foundation for backend and full-stack development.
You should also explore security topics like cross-site scripting (XSS) and cross-site request forgery (CSRF). Cookies play a central role in both vulnerabilities and defenses, making them a critical concept for secure web development.
Another valuable direction is experimenting with different storage mechanisms, such as localStorage, sessionStorage, and IndexedDB. Comparing these options in real projects will help you make better architectural decisions.
The more you build and experiment, the more intuitive these concepts will become.
Frequently asked questions about HTTP cookies#
What are HTTP cookies used for?#
HTTP cookies are used for session management, user personalization, and tracking. They allow websites to remember user information such as login sessions, preferences, and browsing behavior across multiple requests.
Are HTTP cookies secure?#
Cookies can be secure if configured properly. Using attributes like Secure, HttpOnly, and SameSite helps protect cookies from attacks such as cross-site scripting (XSS) and cross-site request forgery (CSRF).
What is the difference between session cookies and persistent cookies?#
Session cookies are temporary and deleted when the browser is closed, while persistent cookies remain stored until a specified expiration date or duration is reached.
What is SameSite in cookies?#
SameSite is a cookie attribute that controls whether cookies are sent with cross-site requests. It helps prevent certain types of attacks by restricting how cookies are shared between different domains.
Can cookies store large amounts of data?#
No, cookies are limited in size (around 4 KB per cookie) and should only store small pieces of data like session IDs. Larger data should be stored using alternatives like localStorage or databases.
Do modern browsers block third-party cookies?#
Many modern browsers restrict or block third-party cookies by default to improve user privacy. Developers must explicitly configure cookies and sometimes use alternative approaches for cross-site tracking or authentication.
Wrapping up#
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!