Efficiently using Session & Flash in Play framework

Table of contents
Reading Time: 2 minutes

Play framework is being the love of every Scala developer now a days. In this post we’ll learn about using Session & Flash scopes in Play framework.

Play has a stateless architecture so in order to keep the data across multiple HTTP request we can use Session & Flash. Session and Flash data are not stored by the server but are added to each subsequent HTTP request, using the cookie mechanism. This result in to the limitation of data size that we want to keep in Session or Flash. Generally we can store data up to 4KB in Session or Flash.

Session :

– Data stored in the Session are available during the whole user session.
– Cookie values are signed with a secret key so the client can’t modify the cookie data.

Storing the data in Session :

For the very first request we can store the values in Session as

This’d start a new session and store the values.

For the subsequent requests in order to store more data in session you can use it like :

This’d keep the previously stored values in session and would add more data in Session.

Retrieving the data from session:

Discarding the whole session :

Session Expiry : Session expires when the user closes the web browser.

Flash :

– Data stored in the Flash scope are available to the next request only.
– Cookie is not signed, making it possible for the user to modify it.

Storing the data in Flash :

Retrieving the data from Flash:

Retrieving the values on views :

To retrieve the Flash scope value in your view, just add an implicit with Flash:

6 thoughts on “Efficiently using Session & Flash in Play framework2 min read

    1. If I need to manage session, how can I do that?
      I am building an android app and integrating it with REST services (Play + Scala). I need to check whether the requests are Ok or not

    2. Is there a way we can access request or use request.session.get(“”) something in some normal method and not an action? I need to access request but want to call some other method from it and not return some result

  1. Session never expire by just closing browser or just using logout button. As HTTP is a stateless protocol, so we use session-id to keep track of multiple HTTP request of authenticated user and differentiate from other users as well. So, session-id have same importance as password have. After logout, if session-id is not expire by the server end. Then, user don’t need their credentials again to log-in. IF any how anyone get session-id, HE/SHE log-in into the application. So, Session – id must be expire by server end.

Comments are closed.