Injecting Environment Variables into a React application

  • Daniel Pedroso
  • January 22, 2019

Embedding environment variables into your front-end app

If you are buiding an SPA, chances are your front-end is already completely decoupled from your API. That said, it is absolutely incredible how often teams will end up tightly coupling them again by injecting variables into the initial HTML page on every request (e.g. injecting a Google Analytics ID via a Pug/Haml/Jade template served by a Node/Rails/Whatever service).

Now, there’s a very easy way around this. It doesn’t work for values that are session-dependent (if you do have values that are session-dependent and they cannot be requested via AJAX calls, I would say there’s a bigger issue here), but it works for values that you have access to in build time.

If you are using create-react-app, it’s about as easy as it gets: you just need to populate the .env file in your CI/CD pipeline. Any variables that begin with REACT_APP_ will be available to you from the JavaScript side.
Example:

.env

REACT_APP_PUSHER_APP_KEY=the_pusher_app_key

pusher.js

import Pusher from 'pusher-js';

const pusher = new Pusher(process.env.REACT_APP_PUSHER_APP_KEY, { ...config });

If you’re not using create-react-app and/or you’ve ejected your app configuration and want something a bit more manual, you can define a webpack plugin.

webpack.config.js

import webpack from 'webpack';

module.exports = {
  // Your webpack config here
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        'PUSHER_APP_KEY': process.env.PUSHER_APP_KEY,
        'ANOTHER_VALUE': 'not comming from an environment variable'
      }
    })
  ]
};

Easy!