Chapter 4. Cookies
The HTTP protocol is stateless. This means that every request made must include all the information needed in order for the web server to serve the correct response. At least, in theory! In practice, that isn’t how we experience the Web as users. As we browse around a shopping site, the website “remembers” which products we already viewed and which we placed in our basket—we experience our journeys on the Web as connected experiences.
So how does this work? Additional information is being saved and sent with our web requests through the use of cookies. Cookies are just key/value pairs; simple variables that can be stored on the client and sent back to us with future requests. A user’s choice of theme or accessibility settings could be stored, or a cookie could be dropped to record something as simple as whether the user has visited the site before, or dismissed a particular alert message that was shown.
Cookie Mechanics
This isn’t the moment where I tell you how to bake cookies, although the instructions do read a little bit like a recipe. What happens when we work with cookies goes something like this (see Figure 4-1):
- A request arrives from the client, without cookies.
- Send the response, including cookie(s).
- The next request arrives. Since cookies were already sent, they will be sent back to us in these later requests.
- Send the next response, also with cookies (either changed or unchanged).
- Steps 3–4 are repeated indefinitely.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access