SECRET_KEY_BASE vs RAILS_MASTER_KEY
| SECRET_KEY_BASE | RAILS_MASTER_KEY | |
|---|---|---|
| Purpose | root secret for signing and encrypting cookies, sessions, signed IDs, Active Storage URLs | decrypts config/credentials.yml.enc |
| Format | 128 hex characters (64 bytes) | 32 hex characters (16 bytes) |
| Where it lives | ENV["SECRET_KEY_BASE"] or inside the credentials file | config/master.key or ENV["RAILS_MASTER_KEY"] |
| If you replace it | users are logged out, signed links break | the existing credentials file can't be read |
| Command | bin/rails secret | created by bin/rails credentials:edit |
In production, Rails reads SECRET_KEY_BASE from the environment first and falls back to secret_key_base in the credentials. Setting the environment variable is the simplest option on most hosts.
Setting the keys in production
# Heroku heroku config:set SECRET_KEY_BASE=<128 hex chars> heroku config:set RAILS_MASTER_KEY=$(cat config/master.key) # Fly.io fly secrets set SECRET_KEY_BASE=<128 hex chars> # Kamal: .kamal/secrets + config/deploy.yml env.secret RAILS_MASTER_KEY=$(cat config/master.key)
Copy the real config/master.key for RAILS_MASTER_KEY in existing apps. The generated master key above is for new credentials files only.
Docker: precompiling assets without the real key
# Rails 7.1+: a throwaway secret only for this step RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile
Rotating SECRET_KEY_BASE without logging everyone out
Rails can read cookies signed with an old secret and rewrite them with the new one. Add a rotation for the transition period:
# Rails 7+ defaults (SHA256 key derivation). Matches the Rails guide pattern.
Rails.application.config.after_initialize do
old_secret = ENV["OLD_SECRET_KEY_BASE"]
next if old_secret.blank?
config = Rails.application.config.action_dispatch
key_generator = ActiveSupport::KeyGenerator.new(
old_secret, iterations: 1000, hash_digest_class: OpenSSL::Digest::SHA256
)
config.cookies_rotations.tap do |cookies|
cookies.rotate :encrypted, key_generator.generate_key(
config.authenticated_encrypted_cookie_salt, ActiveSupport::MessageEncryptor.key_len
)
cookies.rotate :signed, key_generator.generate_key(config.signed_cookie_salt)
end
endRemove OLD_SECRET_KEY_BASE once sessions created before the switch have expired. If the old secret leaked, skip the rotation so stolen cookies stop working immediately. For Ruby's environment loading in general, see the Rails .env generator.