Cookies

Discover what cookie attributes are and the best practices for setting them to ensure protection from attacks like Cross-Site Scripting and Cross-Site Request Forgery.

What is a cookie?

Cookies provide a way to store server-sent data on the browser. The browser can then send the cookies back to the server in subsequent requests. Why would we want to do this? In theory, HTTP and web application servers are generally stateless, meaning that HTTP requests can be made independently of one another and each call contains all of the data necessary to successfully complete. The web servers themselves shouldn’t maintain any information from request to request related to the user’s active browsing session. However, in reality, this becomes extremely hard for developers that need to link a series of requests to the same user.

Press + to interact

For instance, imagine an anonymous user that visits an e-commerce site for the first time. Initially, there are no cookies when the first request is sent to the server. However, the server can create a unique identifier for the user and return a Set-Cookie header that contains this identifier in the first response.

Each time the user adds an item to their shopping cart, another request is made to the server, but this time, it includes a Cookie header that contains the unique identifier that the server can use to connect related requests. The web server does this by linking the identifier to a session (data stored on the server related to an active browser connection). Sessions can store anything ranging from shopping cart information to authentication data.

For session-based authentication, the server creates a session for each user after they log in. The session ID is then stored in a cookie on the user’s browser and sent along with each request. The server uses the session ID to look up any active sessions on the backend and if found, sends back a response with the corresponding state.

Cookie attributes

We learned that cookies can be set via a Set-Cookie header. A server response may contain many Set-Cookie headers because only one cookie is allowed to be set per header. However, each cookie may contain many attributes that define how the cookie can be used.

Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>; Max-Age=<number>; Domain=<domain-value>; Path=<path-value>; SameSite=Strict; Secure; HttpOnly
Multiple attributes being set for a cookie

Let’s take a closer look at each attribute.

Expires

The Expires attribute sets the exact time when a cookie should be cleared. If unspecified, the cookie becomes a session cookie, which is cleared after the user closes their browser. These days, many browsers offer a session restore feature that saves information associated with each tab and restores them all the next time the browser is used, even if the browser was closed ...