BigBinary Blog

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

Rails 5.2 expiry option for signed & encrypted cookies

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", expires: + 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.

cookies.encrypted[:firstname] = { value: "Sam", expires: + }

# sets string `Sam` in an encrypted `firstname` cookie for 1 day.

cookies.signed[:lastname] = {value: "Smith", expires: + 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", expires: + 90.minutes}

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

# setting cookie for 90 minutes from current time.

cookies[:username] = { value: "Sam", expires: 90.minutes }

# After 1 hour

> cookies[:username]
> #=> "Sam"

# After 2 hours

> cookies[:username]
> #=> nil
> ~~~
Mohit Natoo in Rails 5.2
09, 2017

You might also like

Recyclable cache keys in Rails

Rails 5.2 DSL for configuring Content Security Policy

Rails 5.2 stops some raw SQL, prevents SQL injections

Rails 5.2 added method write_multi to cache store

Rails 5.2 uses AES-256-GCM authenticated encryption

Subscribe to our newsletter