Setting up Dotenv in Rails

Aman Kumar
1 min readDec 15, 2022

Got all your credentials in Rails App Code. Well, no one wants that 😛, but here we are.

In this article, we will set up separate env files for our server for different configurations (test, development, production). We will go through how to actually implement this using DOTENV in Rails.

First, Add dotenv in Gemfile

gem 'dotenv-rails'

Next, Execute to install the above gem in your repository

bundle install

Now, Add your application configuration to your .env file in the root of your project:


Whenever your application loads, these variables will be available in ENV:

config.fog_directory  = ENV['S3_BUCKET']

Add .env to .gitignore, so that you don’t end up uploading env back in git


That’s It. We have successfully implemented DOTENV in Rails, Go and Put your credentials here and make your code credentials accessible.

I hope this helped 😄.

Let’s dive in a little more,

Setting up Multiple Environments using DOTENV

We can setup different environments in Rails using dotenv, by creating different files for each environment in the format .env.{environment}.

Let’s say I want to have different credentials in test and production, Our code will like as

# .env.production

# .env.test

# .env
# We can keep common configuration inside .env