Cookies, Session ID & Authentication


State-less HTTP and the Reason for Cookies

Cookies are commonly used but also commonly misunderstood. They allow servers to instruct clients to store specific information, such as session ID or token. Cookies were created to address a deliberate aspect of HTTP, which is it's explicit design goal of being state-less. In theory, because HTTP is state-less, if a hundred different users, accessed a given URL, they should all receive the same information.

While this provides an enormous benefit in many (if not most cases) because there is a predictability of what a user will get when they access a URL. For example, you could search something on Google and copy that URL and give it to your friend, and in theory s/he would see the same search results.

In the early days of the Web, software engineers began to realize this state-less aspect of HTTP made it challenging to enable users to shop online. Without keeping track of whether a user is logged in or not, everytime a user would want to add an item to their shopping cart, they would need to re-login. Clearly there needed to be a better solution to this.

Cookies were created to address this issue by allowing users to send a user-specific ID with each request so that the server would know to respond with the correct user's information.

A Brief Authentication Example Using Session ID

To explain how cookies, session ID, and authentication works in Node.js and Express.js. Let's use a hypothetical to-do web app.

When you open up Chrome and log into the web app, the server creates a session object that has a session ID property that's a unique string. The server then instructs in the response that your browser should store this session ID as a cookie on your computer. Typically cookies that store session ID are set to expire as soon as the session ends (i.e. when you exit out of Chrome). While the server sends you the session ID, it will not send the entire session object and will modify the session object by storing information such as username, date accessed, and etc.

Now that you are logged in and have a cookie with a unique session ID, whenever you go to a new page on the web app, your browser sends a request header that includes a cookie property, which is a string that includes the session ID. The cookie property on the request header is parsed by the server and the session ID is matched to a session object using a key-value store (e.g. Javascript object).

On the matched session object, the user's ID, and session information (such as last products visited) can be accessed.

Additional resources:

views