How Cookies and Sessions Work: Complete Beginner's Guide
When you log into a website, add items to a shopping cart, or stay logged in across pages, the site somehow "remembers" you. HTTP itself is completely stateless—every request is independent. Cookies and sessions are the mechanisms that solve this problem and make modern web applications possible.
Understanding how cookies and sessions work is essential for every web developer. It explains authentication, personalization, shopping carts, security risks, and why certain headers and attributes matter.
What Are Cookies?
A cookie is a small piece of data that a server sends to a browser. The browser stores it and automatically includes it in future requests to the same site.
Cookies are simple name-value pairs, for example:
sessionId=abc123xyz
theme=dark
language=en
They allow the server to recognize returning clients without requiring the user to re-authenticate on every single page load.
What Are Sessions?
A session represents a continuous interaction between a client and a server. Because HTTP is stateless, the server needs a way to link multiple requests to the same user.
In practice, the server creates a unique session ID, stores associated data (user ID, cart contents, preferences) on the server side, and sends only the session ID to the browser—usually inside a cookie.
The browser then sends that session ID with every subsequent request so the server can look up the correct session data.
How Cookies and Sessions Work Together
Here is the typical flow when a user logs in:
- The user submits credentials (username and password) via a form or API request.
- The server validates the credentials.
- If valid, the server creates a new session, generates a unique session ID, and stores session data (for example, user ID and login time) in a session store (memory, database, Redis, etc.).
- The server sends a response with a
Set-Cookieheader containing the session ID. - The browser stores the cookie.
- On every future request to that domain, the browser automatically includes the cookie in the
Cookieheader. - The server reads the session ID, retrieves the corresponding session data, and knows which user is making the request.
This is why you can navigate between pages on a site without logging in again.
Anatomy of a Cookie
When a server sets a cookie, it uses the Set-Cookie response header. A typical example looks like this:
Set-Cookie: sessionId=38afes7a8; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600
Key attributes include:
- Name and Value — The actual data (e.g., sessionId=38afes7a8).
- Expires or Max-Age — Controls how long the cookie lives. Without these, it becomes a session cookie that is deleted when the browser closes (though modern browsers with session restore may keep them longer).
- Path — Restricts the cookie to a specific path on the domain.
- Domain — Defines which domains can receive the cookie.
- Secure — Cookie is only sent over HTTPS connections.
- HttpOnly — Prevents JavaScript from accessing the cookie, reducing XSS risk.
- SameSite — Controls whether the cookie is sent with cross-site requests (Strict, Lax, or None). Helps mitigate CSRF attacks.
Session Cookies vs Persistent Cookies
- Session cookies have no Expires or Max-Age. They are intended to last only for the current browser session.
- Persistent cookies have an explicit expiration and survive browser restarts until that time.
Many "Remember me" features use persistent cookies, while regular login sessions often use shorter-lived or session cookies.
How the Browser Handles Cookies
Browsers automatically manage cookies for each domain according to the attributes set by the server. Important behaviors:
- Cookies are scoped to the domain (and optionally subdomains) that set them.
- They are sent only to matching domains and paths.
- Size limits exist (typically around 4 KB per cookie and a limited number per domain).
- Users can clear cookies or block them entirely through browser settings.
Real-World Examples
Shopping Cart
When you add an item to a cart on an e-commerce site, the server either stores the cart in the session (linked by a session cookie) or places the cart data directly in a cookie. As you browse different product pages, the same session or cookie keeps the cart contents available until checkout.
Authentication
After successful login, a session cookie (or a signed authentication token stored in a cookie) keeps you logged in. Every protected page request includes the cookie so the server can authorize the request without asking for credentials again.
Preferences
Theme preference (dark/light mode), language selection, or recently viewed items are often stored in cookies so the experience remains consistent across visits.
Code Example: Setting and Reading Cookies
In a simple Node.js / Express example:
// Setting a session cookie after login
res.cookie('sessionId', 'abc123xyz', {
httpOnly: true,
secure: true, // only over HTTPS
sameSite: 'lax',
maxAge: 24 * 60 * 60 * 1000 // 1 day
});
// Reading the cookie on a later request
const sessionId = req.cookies.sessionId;
if (sessionId) {
// look up session data and proceed
}
On the client side, JavaScript can read non-HttpOnly cookies via document.cookie, but HttpOnly cookies are inaccessible to scripts for security reasons.
Common Misconceptions
- "Cookies store all the user data." — Usually false for sessions. The cookie often holds only an opaque session ID. The actual data lives on the server.
- "Sessions require cookies." — Cookies are the most common transport for session IDs, but alternatives exist (URL rewriting, Authorization headers with tokens).
- "Closing the browser always ends the session." — Session cookies are designed that way, but browsers with session restore and servers with long-lived sessions can behave differently.
- "All cookies are tracking cookies." — First-party session and preference cookies are essential for functionality. Third-party tracking cookies are a different concern.
Security Considerations and Best Practices
- Always set
HttpOnlyon session cookies to prevent JavaScript access. - Use the
Secureflag so cookies travel only over HTTPS. - Set an appropriate
SameSitevalue (Lax or Strict) to reduce CSRF risk. - Keep session IDs long, random, and unpredictable.
- Regenerate the session ID after login to prevent session fixation attacks.
- Implement proper session expiration and idle timeouts on the server.
- Do not store sensitive data (passwords, full credit card numbers) in cookies.
- Prefer short-lived access tokens + refresh tokens for modern APIs when possible.
Key Takeaways
- HTTP is stateless; cookies and sessions provide the missing memory.
- A cookie is a small piece of data stored by the browser and sent back automatically.
- A session is server-side state linked to the client via a session ID (usually carried in a cookie).
- Proper cookie attributes (HttpOnly, Secure, SameSite) are critical for security.
- Understanding this mechanism is fundamental to building authentication, shopping carts, and personalized experiences.
FAQ
What is the difference between a cookie and a session?
A cookie is data stored on the client (browser). A session is data stored on the server. The cookie usually carries a session ID that lets the server find the correct session data.
Are cookies necessary for sessions?
They are the most common and convenient way to transport a session ID, but not the only way. Tokens in Authorization headers or other mechanisms can also work.
What happens if a user disables cookies?
Session-based authentication and many site features will break unless the application provides an alternative (such as token-based auth or URL rewriting).
How long do cookies last?
It depends on the Expires or Max-Age attributes set by the server. Session cookies without those attributes are intended to last only for the browser session.
Can JavaScript read all cookies?
No. Cookies marked HttpOnly cannot be accessed by JavaScript. This is a deliberate security measure.
What is session hijacking?
It is an attack where an attacker steals a valid session ID (often from a cookie) and impersonates the user. Using HTTPS, HttpOnly, Secure, and SameSite attributes significantly reduces this risk.
Should I store sensitive data in cookies?
Avoid storing sensitive information in cookies. Prefer storing a random session ID in the cookie and keeping sensitive data on the server.
Related Articles:
- How HTTP Works
- How DNS Works
- How Authentication Works
- How Browsers Render Web Pages
- REST API Architecture Explained