tezvyn:

HTTP Cookies: State for a Stateless Web

AI-drafted, machine-checkedSource: Wikipedia: HTTP cookieintermediate

Think of a cookie as a server's nametag for your browser. Since HTTP is stateless, this nametag helps the server remember you across requests for logins, shopping carts, or personalization. The main footgun is security: always use security flags.

WHY IT EXISTS HTTP is a stateless protocol. Each request from a client to a server is an independent transaction, unrelated to any previous requests. This makes tasks like keeping a user logged in or remembering items in a shopping cart impossible without a way to maintain state. Cookies were created to solve this by letting a server store small pieces of information on the client.

THE MENTAL MODEL A cookie is like a coat-check ticket. You give your identity to the server, and it gives you a ticket (the cookie) to hold onto. On your next visit, you present the ticket, and the server can retrieve your session details without having to remember you personally. The browser is responsible for holding the ticket and showing it every time you talk to that specific server.

HOW IT WORKS The process uses two HTTP headers. First, when a server wants to create a cookie, its response includes a Set-Cookie header with a key-value pair and optional attributes (like Expires, Max-Age, Domain, Path, Secure, HttpOnly, SameSite). For every subsequent request to that same server, the browser automatically includes a Cookie header containing all relevant key-value pairs. The server reads this header to "remember" the client.

WHEN TO USE IT Use cookies for managing user sessions, like keeping a user logged in after they authenticate. They are also suitable for storing user preferences, such as a chosen theme (dark/light mode) or language. Another common use is for tracking user behavior across a site for analytics purposes.

WHEN NOT TO USE IT Avoid storing large amounts of data in cookies; browsers have size limits (typically around 4KB). Never store highly sensitive information like passwords or credit card numbers directly in a cookie. For client-side state that doesn't need to be sent to the server on every request, consider using Web Storage APIs like localStorage or sessionStorage instead.

ONE CANONICAL EXAMPLE A user logs into a site. The server verifies their credentials, creates a session ID, and sends it back in a response header: Set-Cookie: session_id=abc123xyz; HttpOnly; Secure. For all future requests to that site, the browser automatically sends Cookie: session_id=abc123xyz. The server uses this ID to look up the user's session data and confirm they are still logged in.

Read the original → en.wikipedia.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.