When creating a Ruby on Rails backend, you may want to utilize an external API or set up JWT. In the case of an external API you will likely need an API key when making requests to the server. If this key is exposed to the public and someone were to find it, you could end up incurring large fees depending on the external APIs charging system. With JWT your token is encoded with a secret. If your secret lives within your code and it exposed to the public, it’s not much of a secret anymore and could be used to steal your user’s information. Something as simple as uploading your project github can expose these private pieces of information to the public and cause financial losses or headaches in the future. So how do we protect this information, while still making our code visible on github?
The dotenv Gem
There are multiple ways to hide stuff from the public when uploading to github, but the method I will be going over today utilizes the dotenv gem.
To use the gem in your Rails project, add the following to your Gemfile:
After saving your Gemfile, run bundle install to install the gem and any dependencies.
Now that we have the gem we will want to create a new file in the root directory of our project. In the terminal navigate to the root directory and enter the following to create our .env file:
This is the file where all our secrets will be stored. To make this file not upload when pushing to Github, we’ll want to add this new file to our .gitignore. Open up the .gitignore file in the root directory and add the following to a new line.
Everything is now setup to protect the data in the file from being exposed via Github, but how do we actually use the .env file?
Using the dotenv Gem
We will first want to update our .env file with the keys we want to store. Open the .env file with a text editor and add a line for each hidden value you will need in your project. Keys should be entered in the following format:
After saving the file, you will now have access to these keys in your rails project using the following:
These values can be stored to variables or interpolated in strings in your code. Now when pushing your project to Github, you can still show off all of your beautiful code to the public without giving away your secrets!
Note regarding Heroku
If you are planning on hosting your Rails project on Heroku, then the .env file will be ignored when pushing your app. Don’t worry though, you won’t have to change your code for Github and Heroku, you just need to add these keys to your project’s config vars with the same key name you did in your .env file and everything will work. For more information on setting up your app’s config vars on Heroku, please reference their site’s article on the subject.