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.

import play.api.mvc.Cookie
import play.api.mvc.DiscardingCookie

Storing the data in Cookie :

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

Ok("Success").withCookies(Cookie("Org", "Knoldus Software LLP"))

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 :-

Ok("Success").withCookies(Cookie("Org", "Knoldus Software LLP", Option(86400)))

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.

One comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s