Rails offers two safe places for secrets: encrypted credentials (config/credentials.yml.enc, decrypted with config/master.key or RAILS_MASTER_KEY) and environment variables read with ENV.fetch. Commit the encrypted file but never the master key. Use ENV.fetch("NAME") to fail fast when a value is missing.
Read the key from the environment
# config/initializers/stripe.rb
Stripe.api_key = ENV.fetch("STRIPE_SECRET_KEY")
# or, from encrypted credentials:
# Rails.application.credentials.dig(:stripe, :secret_key)Local development
Edit encrypted credentials with bin/rails credentials:edit, which opens the decrypted content in your editor and re-encrypts on save. Rails generates config/master.key and adds it to .gitignore. Per-environment files (config/credentials/production.yml.enc with production.key) are supported. For environment variables, many teams use the dotenv-rails gem in development with a git-ignored .env.
Production
Provide RAILS_MASTER_KEY as an environment variable from your platform's secret store so the app can decrypt credentials at boot, or set individual secrets as variables. Back up the master key somewhere other than the repository, because losing it makes the encrypted file unreadable. Rotate keys by editing credentials, and rotate the master key by re-encrypting under a new one.
Mistakes to avoid
- Committing
config/master.keyor a.envfile; the key unlocks everything in the credentials file. - Putting secrets in
config/secrets.ymlordatabase.ymlas plaintext literals. - Logging
Rails.application.credentialsorENV.to_h, or enabling verbose parameter logging without filtering. Add sensitive names toconfig.filter_parameters. - Losing the master key without a backup, which makes the committed encrypted file useless.
When an AI agent works on your Ruby on Rails project
Coding agents run inside your project folder, so they can read the same .env file your app reads. BotPassword injects keys at run time instead: the agent calls the run_with intent through the MCP server and the process gets the variables it needs while the agent sees only redacted output. Planned: bpw run, a CLI form of the same.
Frequently asked questions
Should I use Rails credentials or environment variables?
Either is acceptable. Credentials keep secrets versioned and encrypted in the repo with only the key managed separately; environment variables suit platforms that inject secrets for you. Many apps use both.
Where does RAILS_MASTER_KEY go in production?
Set it as an environment variable from your host's secret store. It must never be committed, because it decrypts the credentials file.
Should I keep API keys in a .env file for Ruby on Rails?
A .env file that is git-ignored is fine for local development, but every process and every AI coding agent running in that folder can read it. Load secrets into the environment at run time from a password manager or secrets manager instead, so no plaintext file sits in the project.