A cookie is a small piece of text a website asks your browser to store and hand back on every later request. It is how a site that forgets you between clicks can still keep you logged in, remember your settings and hold on to your basket.
Why the web needs cookies
HTTP, the protocol your browser uses to talk to websites, is stateless. Each request stands on its own: when the server answers one, it keeps no built-in memory of who asked. Load the home page, then the basket page, and as far as HTTP is concerned those are two strangers knocking on the door.
That is fine for a page that looks the same to everyone. It breaks down the moment a site needs to know it is still you: after you sign in, when you pick dark mode, or when you add something to a basket and move on to the next page.
Cookies fill that gap. The server gives your browser a small note, the browser keeps it, and from then on it attaches the note to every request it sends to that site. The server reads the note and knows who it is dealing with.
How a cookie travels
A cookie moves in two HTTP headers, one in each direction:
- The server sends
Set-Cookiein a response. That tells the browser: store this name and value. - On every later request to the same site, the browser sends
Cookiewith the stored name and value in it.
The browser does the second part on its own. Your page's code doesn't have to remember to attach anything, which is exactly what makes cookies convenient for staying logged in.
Here is the whole round trip, from a first visit to a return visit:
A cookie set on one visit and sent back on the next
Step 1 of 8: On your first visit the request carries no cookie, so the server has no idea who you are.
Wondering how this was made? How we make these