How to use Cookies in Play framework

Table of contents
Reading Time: 2 minutes

Play framework is being used by every Scala developer now a days. In this post we’ll learn about using Cookies in Play framework.

Play has a stateless architecture so in order to keep the data across multiple HTTP request we can use Session & Flash. But both Session & Flash loose data as soon as browser is closed. So, to retain data even after closing the browser, we can use Cookies in Play framework. Cookies are not stored by the server, instead they are stored at the client side.

  • Data stored in cookies are available till they expire or they are cleaned by user.
  • We can set the expiration time of cookies.
  • They can be made secure, but only for sites working on HTTPS.
  • They can be used like a Scala collection.

Before start using Cookies in Play framework these two libraries have to imported.

Storing the data in Cookie :

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

This will save a Cookie in browser with name “Org” and store the value “Knoldus Software LLP” in it.

We can also set Cookies’ expiration time :-

You’ll have to give time in Seconds as Option(Int). Here we have set the expiration time = 86400 seconds i.e., 1 day. So, the Cookie will expire/will get delete after 1 day from browser. Like this, Cookie can be set for more/less time according to Application.

Retrieving data from Cookie:

We can retrieve data from Cookie by using “request”.

Discarding/Deleting the whole Cookie:

This will discard/delete the Cookie from browser even if the expiration time is not elapsed.

To check whether Cookies are being added in browser or not you can check it in your browser settings.

Written by 

Himanshu Gupta is a software architect having more than 9 years of experience. He is always keen to learn new technologies. He not only likes programming languages but Data Analytics too. He has sound knowledge of "Machine Learning" and "Pattern Recognition". He believes that best result comes when everyone works as a team. He likes listening to Coding ,music, watch movies, and read science fiction books in his free time.

1 thought on “How to use Cookies in Play framework2 min read

Comments are closed.