Hiding Sensitive Info in React and Rails

Doug Schallmoser
2 min readDec 30, 2020

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:

  1. Create a new file named .env in the root of your React application.
  2. Because you created your app using create-react-app, the engine is able to read keys that start with REACT_APP. Inside your .env file, add the following line:
    REACT_APP_GOOGLE_API_KEY = insert_key_here
  3. 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
  4. 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.
  5. 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 utilize API_KEY in your code.
    const API_KEY = process.env.REACT_APP_GOOGLE_API_KEY
  6. 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:

  1. Add dotenv-rails to your Gemfile. Then run bundle install.
  2. Create a new file named .env in the root of your Rails application.
  3. 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
  4. 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:

  1. Once your app is successfully deployed on Heroku, click on the Settings tab.
  2. Scroll down to the Config Vars section and click Reveal Config Vars.
  3. 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
  4. Click add.

That’s it!

Find me on Github:
https://github.com/dougschallmoser

--

--