Chapter 9. Sessions

HTTP is a stateless protocol. Although some view this as a disadvantage, advocates of RESTful web development laud this as a plus. When state is removed from the picture, we get some automatic benefits, such as easier scalability and caching. You can draw many parallels with the nonmutable nature of Haskell in general.

As much as possible, RESTful applications should avoid storing state about an interaction with a client. However, it is sometimes unavoidable. Features like shopping carts are the classic example, but other, more mundane interactions like proper login handling can be greatly enhanced by correct usage of sessions.

This chapter will describe how Yesod stores session data, how you can access this data, and some special functions to help you make the most of sessions.

clientsession

One of the earliest packages spun off from Yesod was clientsession. This package uses encryption and signatures to store data in a client-side cookie. The encryption prevents the user from inspecting the data, and the signature ensures that the session cannot be tampered with.

It might sound like a bad idea from an efficiency standpoint to store data in a cookie. After all, this means that the data must be sent on every request. However, in practice, clientsession can be a great boon for performance:

  • No server-side database lookup is required to service a request.

  • We can easily scale horizontally: each request contains all the information we need to send a response. ...

Get Developing Web Apps with Haskell and Yesod, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.