Cookies
Cookies are small pieces of data (name-value pairs) stored by the browser and automatically sent to the server with every HTTP request to the matching domain, most commonly used for session management, authentication, and user preferences.
Explanation
The server sets a cookie via the Set-Cookie HTTP response header. The browser stores the cookie and includes it in the Cookie request header for all subsequent requests to that domain. Cookies persist until they expire (set by the Expires or Max-Age attribute) or until explicitly deleted. Without an expiry, the cookie is a "session cookie" that disappears when the browser closes. Cookie security attributes matter enormously: HttpOnly (the cookie is inaccessible to JavaScript — document.cookie can't read it — protecting against XSS attacks that steal session cookies), Secure (the cookie is only sent over HTTPS, protecting against network eavesdropping), SameSite (controls whether the cookie is sent with cross-site requests — SameSite=Strict prevents CSRF attacks by not sending the cookie on cross-origin requests, SameSite=Lax is a useful middle ground, SameSite=None requires Secure and allows cross-site usage for embedded iframes). Domain and Path attributes control which requests the cookie is sent with: a cookie set with Domain=example.com is sent to all subdomains (app.example.com, api.example.com); a cookie set with Path=/api is only sent to requests under /api. Cookie size is limited (~4KB per cookie, ~50 cookies per domain). For larger data, store an identifier in the cookie and the actual data in a server-side session or database. Third-party cookies (set by a domain other than the page the user is on) are being phased out by browsers for privacy reasons, which has major implications for cross-site tracking and advertising.
Code Example
javascript// Setting cookies server-side (Express.js)
const express = require('express');
const cookieParser = require('cookie-parser');
app.use(cookieParser());
// Set a secure session cookie
app.post('/login', async (req, res) => {
const user = await authenticate(req.body);
if (!user) return res.status(401).json({ error: 'Invalid credentials' });
// Set HttpOnly + Secure + SameSite for session cookie
res.cookie('sessionId', createSession(user), {
httpOnly: true, // no JS access — XSS protection
secure: true, // HTTPS only
sameSite: 'lax', // CSRF protection
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days in ms
path: '/',
});
res.json({ message: 'Logged in' });
});
// Read cookie in middleware
app.use((req, res, next) => {
const sessionId = req.cookies.sessionId;
if (sessionId) req.user = getSession(sessionId);
next();
});
// Delete cookie on logout
app.post('/logout', (req, res) => {
res.clearCookie('sessionId');
res.json({ message: 'Logged out' });
});
Why It Matters for Engineers
Cookies are how most authentication systems work. Session cookies link browser requests to server-side user sessions; JWT cookies store authentication tokens. Getting cookie security attributes wrong — forgetting HttpOnly, omitting Secure, or using SameSite=None carelessly — creates serious security vulnerabilities that lead to session hijacking and CSRF attacks. Understanding cookies also means understanding the difference between cookie-based auth and token-based auth (JWT in localStorage), and why HttpOnly cookies are generally safer for authentication than tokens in localStorage (localStorage is accessible to any JavaScript, including injected malicious scripts).
Learn This In Practice
Go deeper with the full module on Beyond Vibe Code.
Web Development Fundamentals → →