4.5. Cookies#

4.5.2. Introduction#

HTTP is a stateless protocol, meaning that each request made by a client (browser) to a server is independent. However, many web applications require stateful behavior, such as keeping users logged in, remembering preferences, and managing shopping carts.

To get around this HTTP uses cookies, which are small pieces of data that a web server sends to a user’s browser, which the browser then stores and sends back with subsequent requests.

Note

This allows web applications to maintain a session, which will be explained in a later section.

Step 1: Server Sends a Cookie to the Browser

../../_images/cookie_1.png

A server can add a Set-Cookie header in the HTTP response.

For example, the header of a HTTP response containing a cookie would look like:

HTTP/1.1 200 OK
Set-Cookie: session_id=abc123; HttpOnly; Secure; SameSite=Strict
Content-Type: text/html

In this example: the server sets a cookie (session_id=abc123). The other attributes are explained further down the page.

Step 2: Browser Stores the Cookie

../../_images/cookies_2.png

The browser reads the Set-Cookie header and stores the cookie value. The next time the user makes a request to the same site, the browser automatically includes the cookie in the request.

Step 3: Browser Sends the Cookie Back to the Server

../../_images/cookies_3.png

On subsequent requests, the browser attaches the cookie to the request in the Cookie header.

For example:

GET /dashboard HTTP/1.1
Host: example.com
Cookie: session_id=abc123

The server can then read the cookie, identify the user and respond accordingly.

4.5.5. Setting Multiple Cookies#

A server can set multiple cookies in one response. Each cookie is sent on separate lines in the response header.

For example, setting three cookies at once might look like:

HTTP/1.1 200 OK
Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure; SameSite=Strict
Set-Cookie: csrf_token=xyz789; Path=/; HttpOnly; Secure
Set-Cookie: theme=dark; Path=/; Max-Age=86400
Content-Type: text/html; charset=UTF-8

The client would then send all three cookies back in subsequent requests on a single line.

For example:

GET /dashboard HTTP/1.1
Host: example.com
Cookie: session_id=abc123; csrf_token=xyz789; theme=dark
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9

4.5.6. Session vs Persistent Cookies#

Session cookies are created when Expires is not set. Such cookies will be deleted when the web browser window closes.

Persistent cookies are created when Expires or Max-Age are set. These cookies will be stored by the browser until these times are reached.