Managing ENV variables with dotenv
The idea of using a .env file to manage environment variables in development and test environments has become a standard across many programming languages and frameworks. You may also already be using a library named dotenv to do the managing for you, whether you are using Ruby, JavaScript, Python or any other language (in my research I found that there are at least 22 languages with native dotenv libraries out there).
So why would I bother writing about it as a reason to love Ruby in particular?
Well, the first dotenv library was conceived and implemented in Ruby by Brandon Keepers. And Brandon got the .env file idea from Heroku (a PaaS originally created to host Ruby on Rails applications) and foreman (a Ruby library for running Heroku Procfiles on local computers).
Using the dotenv library is simple enough. After adding it to your Gemfile, just:
require "dotenv/load"
This will load the environment variables defined in a .env file in the root of your project into ENV when your application starts.
Within Rails applications we can instead use the dotenv-rails gem, it will automatically load the .env file and also look for .env.local, .env.#{Rails.env} and .env.#{Rails.env}.local files, which allows us to have different environment variables for different environments.
The .env file in version control controversy
Most variants of dotenv advertise that the .env file should not be committed to version control, since it may contain sensitive credentials. But in fact, the original dotenv library for Ruby has consistently asserted a preference for committing a .env file with non-sensitive development credentials to version control, as a way to make it easier for new developers to get started with the project. Sensitive credentials can then instead be added to a .env.development.local file.
At my job at Mynewsdesk, we happily commit our .env files to version control without fear. This provides a zero-friction onboarding experience for our applications, and we have yet to have any issues with it, since we are stringent with using separate production credentials for all third-party services and only commit sandbox account credentials. So far so good 🤞
History
The pivotal moment was when Heroku introduced The Twelve-Factor App manifesto back in 2011. In particular, the third factor: Store config in the environment. This was a game changer for how to think about configuration and environment variables, and it was the catalyst for the creation of the original dotenv library.
The first release of Foreman was on May 20, 2010. The support for loading a .env file came later in version 0.16, released May 13, 2011, as mentioned in this GitHub comment.
The first version of dotenv was released on July 24, 2012.
The first three external ports of dotenv were:
- phpdotenv in January 2013
- django-dotenv in June 2013
- dotenv (for Node.js) in July 2013