Hiding Sensitive Info in React and Rails
In order to secure sensitive information such as API keys from other people’s eyes, it is imperative that you hide them from your public repository. You do not want your keys visible in any of your public commits. There are simple processes you can take to hide sensitive information in both your React frontend application as well as your backend Rails application.
Hiding API Keys in React
There is a very simple way to hide your API keys if you built your React application using create-react-app
:
- Create a new file named
.env
in the root of your React application. - Because you created your app using
create-react-app
, the engine is able to read keys that start withREACT_APP
. Inside your.env
file, add the following line:
REACT_APP_GOOGLE_API_KEY = insert_key_here - Keep in mind, you can name this variable anything you want as long as it starts with
REACT_APP
. So I could also do:
REACT_APP_MONKEY_HEAD = insert_key_here - In your root directory there is a file named
.gitignore
. Add.env
to this file. This ignores your.env
file when pushing to Github, so your sensitive information is not shown to the public. - You can now use the API key in any component inside your React application. Set a variable named anything you want equal to the variable just created in the
.env
file. Just like below. Wherever you need access to the key, just utilizeAPI_KEY
in your code.
const API_KEY = process.env.REACT_APP_GOOGLE_API_KEY - If you are in production mode, don’t use this method as environmental variables are embedded into the build which means anyone can see your sensitive variables. This is to be utilized for development mode only.
Hiding Keys/Secrets in Rails
This example is how I hide my Github Key and Secret when utilizing Omniauth for third party user authentication:
- Add
dotenv-rails
to your Gemfile. Then runbundle install
. - Create a new file named
.env
in the root of your Rails application. - Inside your
.env
file, add the information you would like to be kept hidden. Here, I have two lines:
GITHUB_KEY=insert_key_here
GITHUB_SECRET=insert_secret_here - In order to gain access to this information inside your application, you simply assign a variable to your key, such as:
my_key = ENV[‘GITHUB_KEY’]
my_secret= ENV[‘GITHUB_SECRET’]
Using Hidden Keys in Heroku
In order to utilize your API/hidden information when your app is deployed live, follow these steps:
- Once your app is successfully deployed on Heroku, click on the
Settings
tab. - Scroll down to the
Config Vars
section and clickReveal Config Vars
. - In the empty KEY field input your key and in the empty VALUE field enter your sensitive information:
KEY = GITHUB_KEY
VALUE = insert_key_here - Click
add
.
That’s it!
Find me on Github:
https://github.com/dougschallmoser