Sessions

July 6, 2010 12:00 am

Avatar Michael Snoyman

This post discusses the session API as present in Yesod 0.4. This version has not been released yet, but you can see the Haddocks online. The API is not much different from previous versions, but the names have changed a bit.

Sessions

Most web frameworks provide some notion of user sessions, where you can store small bits of information for each user. In the case of Yesod, we use the clientsession package (also written by yours truly) to store data in an HTTP cookie. While this might sound insecure and inefficient at first, it's not:

Like most frameworks, the sessions are simple key-value stores. There are three basic operations on a session:

Please note that the setSession and deleteSession functions do not affect the outcome of a call to lookupSession within a single request. In other words:

do
    val1 <- lookupSession "key"
    setSession "key" "newvalue"
    val2 <- lookupSession "key" -- val1 == val2, not "newvalue"

Messages

Messages are built on top of sessions. The situation is a common one in web development: the user performs a POST request, you make a change, and want to simultaneously tell the user that the request suceeded and redirect them to a new page. Yesod provides a pair of functions to make this very easy:

In my projects, I will often put a call to getMessage in the defaultLayout function and know that any messages I set with setMessage will be displayed on the next page the user views.

Ultimate Destination

Not to be confused with a horror film, this concept is used internally in the Yesod authentication module. Simply put, let's say a user requests a page that requires authentication. Clearly, you need to send them to the login page. A well-designed web app will then send them back to the first page they requested. That's what we call the ultimate destination.

blog comments powered by Disqus