Securing Credentials in a Rails App with dotenv
In this guide we will learn how to secure our API credentials using the dotenv gem.
Guide Tasks
  • Read Tutorial

It's very important that our API credentials are secured since if a hacker accessed them he or she could use the keys to spam users with text messages. With that in mind in this guide we will learn how to secure our API credentials using the dotenv gem.

Let's add the gem to the Gemfile:

# Gemfile

gem 'dotenv-rails', :groups => [:development, :test]

After running bundle we can create a new file at the root of the application named .env:

touch .env

Now before we can use this file let's make sure that we add it to the gitignore file so that our credentials don't get checked into source control. At the end of the file add this code:

# .gitignore

/.env

We can verify that this is working by running git status and our .env file shouldn't show up as shown below, this means that when we push the code up to the github repository that our API credentials won't be shared with the world.

large

Now we can add our credentials like this:

TWILIO_ACCOUNT_SID=YOURACCOUNTSID
TWILIO_AUTH_TOKEN=YOURAUTHTOKEN
TWILIO_PHONE_NUMBER=+14322034437

To confirm that Rails is able to access the values we can test this in the console by running:

ENV['TWILIO_PHONE_NUMBER']

And this should print out the phone number, as shown below:

large

This shows that everything is working and now we are free to work with the API without having to be afraid of hackers grabbing our credentials. In the next few guides we'll walk through how to implement SMS sending functionality.

Resources