---
title: "Rails 5.2 expiry option for signed & encrypted cookies"
description:
  "Rails 5.2 adds expiry option for signed and encrypted cookies and adds
  relative expiry time"
canonical_url: "https://www.bigbinary.com/blog/expirty-option-for-signed-and-encrypted-cookies-in-Rails-5-2"
markdown_url: "https://www.bigbinary.com/blog/expirty-option-for-signed-and-encrypted-cookies-in-Rails-5-2.md"
---

# Rails 5.2 expiry option for signed & encrypted cookies

Rails 5.2 adds expiry option for signed and encrypted cookies and adds relative
expiry time

- Author: Mohit Natoo
- Published: October 9, 2017
- Categories: Rails 5.2, Rails

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

```ruby
cookies[: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](https://blog.bigbinary.com/2013/03/19/cookies-on-rails.html).
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](https://github.com/rails/rails/pull/30121)
as well.

```ruby
cookies.encrypted[:firstname] = { value: "Sam", expires: Time.now + 1.day }

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

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

```ruby

# setting cookie for 90 minutes from current time.

cookies[: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.

```ruby

# 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
> ~~~
```

## Links

- [Human page](https://www.bigbinary.com/blog/expirty-option-for-signed-and-encrypted-cookies-in-Rails-5-2)
