Rails 5.2 expiry option for signed & encrypted cookies

Mohit Natoo

By Mohit Natoo

on October 9, 2017

This blog is part of our  Rails 5.2 series.

In Rails 5.1 we have option to set expiry for cookies.

1cookies[:username] = {value: "sam_smith", expires: Time.now + 4.hours}

The above code sets cookie which expires in 4 hours.

The expires option, is not supported for signed and encrypted cookies. In other words we are not able to decide on server side when an encrypted or signed cookie would expire.

From Rails 5.2, we'll be able to set expiry for encrypted and signed cookies as well.

1cookies.encrypted[:firstname] = { value: "Sam", expires: Time.now + 1.day }
2
3# sets string `Sam` in an encrypted `firstname` cookie for 1 day.
4
5cookies.signed[:lastname] = {value: "Smith", expires: Time.now + 1.hour }
6
7# sets string `Smith` in a signed `lastname` cookie for 1 hour.
8

Apart from this, in Rails 5.1, we needed to provide an absolute date/time value for expires option.

1
2# setting cookie for 90 minutes from current time.
3
4cookies[:username] = {value: "Sam", expires: Time.now + 90.minutes}

Starting Rails 5.2, we'll be able to set the expires option by giving a relative duration as value.

1
2# setting cookie for 90 minutes from current time.
3
4cookies[:username] = { value: "Sam", expires: 90.minutes }
5
6# After 1 hour
7
8> cookies[:username]
9> #=> "Sam"
10
11# After 2 hours
12
13> cookies[:username]
14> #=> nil
15> ~~~

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.