DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Can Olcer
Can Olcer

Posted on • Originally published at canolcer.com

Rails: Prevent users from logging out after each deployment

Here's a quick one, and it may be obvious to some of you but I didn't know about it. I noticed that my Rails app (Fugu) kept logging out all users after every deployment.

First, I thought it's an issue with Devise, but it turns out that it's related to a variabled called secret_key_base that Rails uses to sign and encrypt cookies (among other things).

For production, there are multiple places to define secret_key_base. A glance at the Rails soure code shows that Rails looks for it in ENV["SECRET_KEY_BASE"], credentials.secret_key_base, or secrets.secret_key_base.

In my case, I hadn't set up any credentials or secrets, nor was I providing an environment variable.

Digital Ocean (and, as it looks, Heroku) automatically sets the SECRET_KEY_BASE environment variable for you, and it changes with every deployment. And this was the problem. After each deployment, my Rails app couldn't decrypt the existing session cookies anymore beause secret_key_base had a different value, and my users needed to log in again.

To solve the problem, just provide a SECRET_KEY_BASE environment variable in your production server. The simplest way to generate it is to run rake secret in your terminal (make sure you're in a Rails project folder).

Top comments (2)

Collapse
 
sag profile image
Sagar Gupta

TIL something new! Thank you :)

Collapse
 
canolcer profile image
Can Olcer Author

You're welcome!

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: