Maintaining state between browser requests

Cookies

Preliminaries

This note describes the cookie protocol used by the server to maintain state between browser requests.

HTTP is a stateless protocol, so each request for a resource is treated on its own merits. Nevertheless, it is a basic requirement of many applications to keep the state of certain variable data available from request to request. This is particularly important when accessing resources which are restricted to individual users. The cookie protocol is one way for browsers and servers to cooperate towards accomplishing this goal.

Set-cookie header

A server response may include one or more set-cookie headers. These may be created by one of the server's built-in modules, or by a dynamic module developed by a software engineer and configured using the Router.

The only built-in module that creates set-cookie headers, is the RBAC Auth Handler.

A set-cookie header should contain only one key/value pair, joined by an equals-sign. Both the key and the value should be separately encoded using the encodeURIComponent function.

When the browser recieves a response that contains a set-cookie header, it keeps the key/value pair in its internal data structures, associating it with the response's hostname, and remembering it for the duration of the current browser session.

Browser requests

For each subsequent request to that hostname for any resource, the browser will assemble all of the key/value pairs it has remembered into a single cookie header, and send it with the request.

Cookie header

Very early in the request/response cycle the server examines the collection of incoming headers looking for the cookie header. If it exists, it is processed using these steps:

  1. The raw header value is split into cookie tuples at each semicolon separator.
  2. Each cookie tuple is split into a cookie key/value pair at the first equals-sign encountered. When no equals-sign is encountered, the cookie is assigned a null value.
  3. Both the key and value have any URI encoding removed using the decodeURIComponent function.
  4. The key and value are added to the work order's _cookieMap.

Review

Key points to remember:

  • The server informs the browser that some data needs to be remembered, through set-cookie response headers.
  • The browser keeps incoming cookie key/value pairs in its internal data structures.
  • The browser sends a cookie request header to the server with all remembered key/value pairs associated with the request's domain.

Maintaining state between browser requests