Rails: Prevent users from logging out after each deployment
Can Olcer

Can Olcer @canolcer

About: I’m currently working on two open-source projects: Fugu (https://fugu.lol), a privacy-friendly product analytics software, and Mapzy (https://mapzy.io), a store finder.

Location:
Berlin, Germany
Joined:
Oct 29, 2021

Rails: Prevent users from logging out after each deployment

Publish Date: Oct 29 '21
7 2

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).

Comments 2 total

Add comment