This blog is part of our Rails 5.2 series.

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

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

The above code sets cookie which expires in 4 hours.

The expiry 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.

cookies.encrypted[:firstname] = { value: "Sam", expiry: Time.now + 1.day }
# sets string `Sam` in an encrypted `firstname` cookie for 1 day.

cookies.signed[:lastname] =  {value: "Smith", expiry: Time.now + 1.hour }
# sets string `Smith` in a signed `lastname` cookie for 1 hour.

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

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

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

# setting cookie for 90 minutes from current time.
cookies[:username] = { value: "Sam", expiry: 90.minutes }

# After 1 hour
> cookies[:username]
#=> "Sam"

# After 2 hours
> cookies[:username]
#=> nil