Skip to content

Cookies and Sessions

Understand cookies, sessions, and how web apps keep users logged in securely.

What you'll learn

  • What cookies are and how they travel with every HTTP request
  • The key cookie attributes: HttpOnly, Secure, SameSite, Max-Age
  • How server-side sessions work with a session ID cookie
  • The difference between cookies, localStorage, and JWTs

Concept

Cookies and Sessions

Cookies are small key-value pairs that the browser stores and automatically sends with every HTTP request to the matching domain. This automatic behavior is what makes cookies special — unlike localStorage, the server sees them on every request without any client-side code. Cookies are the foundation of authentication on the web: when you log in, the server sets a cookie, and every subsequent request includes it, proving who you are.

How Cookies Work

  1. The server sends a Set-Cookie header in the HTTP response: Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict.
  2. The browser stores the cookie.
  3. On every future request to that domain, the browser includes it: Cookie: session=abc123.
  4. The server reads the cookie, identifies the user, and responds accordingly.

Cookies have a size limit of about 4 KB each. They are sent on every request, so storing large data in cookies bloats every HTTP exchange.

Critical Cookie Attributes

  • HttpOnly — JavaScript cannot read the cookie (via document.cookie). This prevents XSS attacks from stealing the cookie. Always set this on session cookies.
  • Secure — the cookie is only sent over HTTPS, never over plain HTTP. Essential for any sensitive cookie.
  • SameSite — controls when the cookie is sent on cross-site requests. Strict (never send cross-site), Lax (send on top-level navigations, the default), None (always send, requires Secure). This prevents CSRF attacks.
  • Max-Age or Expires — how long the cookie lives. Without this, the cookie is a "session cookie" that clears when the browser closes.

Server-Side Sessions

A session is server-side state identified by a session ID. The flow: the user logs in → the server creates a session in its database/memory → the server sends the session ID in an HttpOnly cookie → on each request, the server reads the cookie, looks up the session, and knows who the user is. The session data (user ID, roles, preferences) lives on the server; the cookie just holds the ID. This is more secure than storing all user data in the cookie itself.

Cookies vs. localStorage vs. JWTs

  • Cookies — sent automatically to the server. Best for session IDs with HttpOnly + Secure + SameSite.
  • localStorage — not sent to the server. Best for non-sensitive client-side preferences.
  • JWTs — self-contained tokens with signed claims. Can go in cookies (secure) or in Authorization headers (for APIs). If in localStorage, they are vulnerable to XSS.

For web apps (same origin), the most secure pattern is a server-side session with an HttpOnly cookie. For APIs consumed by third parties, JWTs in headers are common.

Example

              // Server-side: setting a secure session cookie (Node.js / Express)
app.post("/login", async (req, res) => {
  const user = await authenticate(req.body.email, req.body.password);
  if (!user) return res.status(401).json({ error: "Invalid credentials" });

  // Create a server-side session
  const sessionId = await createSession(user.id);

  // Set the cookie with all security attributes
  res.cookie("session", sessionId, {
    httpOnly: true,     // JS cannot read it — XSS-safe
    secure: true,       // HTTPS only
    sameSite: "strict", // CSRF protection
    maxAge: 86400000,   // 24 hours in ms
    path: "/"
  });

  res.json({ user: { id: user.id, name: user.name } });
});

// Client-side: reading a cookie (only non-HttpOnly ones!)
function getCookie(name) {
  const cookies = document.cookie.split("; ").reduce((acc, c) => {
    const [k, v] = c.split("=");
    acc[k] = v;
    return acc;
  }, {});
  return cookies[name];
}

// The session cookie is HttpOnly, so document.cookie
// does NOT include it — that is the point!
            

The server creates a session and sets a cookie with HttpOnly, Secure, and SameSite=strict for maximum security. The client-side getCookie function can only read non-HttpOnly cookies. The session ID is invisible to JavaScript, so XSS cannot steal it. The server looks up the session on each request.

Try it

  • JWT Decoder

    Decode a JWT to understand token-based auth as an alternative to cookie sessions.

  • Hash Generator

    Session IDs are often hashes — generate one to see how they look.

Common mistakes

The mistake

Setting a session cookie without HttpOnly, exposing it to XSS theft.

The fix

Always set HttpOnly on session and authentication cookies. This prevents JavaScript (including injected XSS scripts) from reading the cookie via document.cookie. The cookie is still sent to the server automatically.

The mistake

Omitting SameSite, leaving the cookie vulnerable to CSRF attacks.

The fix

Set SameSite to 'Strict' or 'Lax' (the modern default). This prevents the cookie from being sent on cross-site requests, which is the mechanism of CSRF attacks. Use Strict for maximum security, Lax if you need top-level cross-site navigation to work.

Related Guides

Practice Cookies and Sessions

2 exercises

Practice Cookies and Sessions

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors