23.2. Cookies

At some point, we’ve all received an alert in our browser that says something like, This website uses cookies. We hear about cookies all the time, but many users don’t think about them too deeply. They either choose Accept or Decline when they see the alert, and then they move on to the next task.

To help us make our Flask applications more efficient, we’ll start by taking a closer look at cookies.

23.2.2. How Cookies Work

One thing we need to remember about cookies is that they are NOT programs. They just store a small amount of data that web servers can use when we visit a site. Here’s a summary of how the cookie process works:

  1. The first time we navigate to a webpage, our browser sends an HTTP request (GET or POST) to the server.

  2. The server sends back an HTTP response, which contains data to display on the page. The response also includes a command to create one or more cookies.

  3. The browser creates the cookie files and stores them on our machine.

  4. When our browser communicates with the server again, it includes all of the saved cookies with the new HTTP request. The server uses the information to help it process the request.

    Cookies set by a specific server can only be sent back to that server. For example, a cookie set by Trinket won’t be sent to the GitHub server.

  5. When the server responds to the new request, it can update the existing cookies or create new ones.

Servers send commends to set cookies, and browsers save them on a user's device.

Servers use commands to set cookies. Browsers create and save cookie files on a user’s device.

Cookies serve several purposes:

  1. To keep us logged into a site.

  2. To store helpful data for the server during our visit. For example:

    1. Our current score in a game we’re playing. If we need to close the tab when our teacher/parent/boss walks by, cookies save our progress until we return.

    2. The contents of a shopping cart. When we select Checkout to complete an online order, cookies identify the items we want to buy.

  3. To track and analyze our behavior.

    1. Have you received targeted adds while searching the web? Cookie data influences what you see!

    2. Watch this short video clip that describes how cookies are used to track your movement on the web.

23.2.3. Check Your Understanding

Question

A cookie is a small program that runs in the browser.

  1. True
  2. False

Question

Where is a cookie file saved?

  1. On a web server
  2. In an open browser application
  3. On the user's device
  4. In the cloud