Using Environment Variables With React & WebPack

There might be times when you’re developing a React app that you want to use environment variables. That may be because you don’t want the values of those variables being pushed to a repo that’s either public or for various other reasons. If you are using DotEnv there’s a couple more steps you have to take to get it working unlike if your using DotEnv in Node. In this short post I’m going to show you how to configure WebPack to make it work.

I usually use NPM for my projects but this should work with Yarn also because there is a dotenv-webpack package for Yarn also.

To start you should install the Dotenv-Webpack module within your project. Note, I’m assuming you already have a project started and are using WebPack to build it already. But to do this run the following command:

npm --save-dev install dotenv-webpack

Once you’ve done that the next thing you have to do is add a configuration to your webpack.config.js file so that Webpack will know how to handle environment variables included within your code. The first thing you do is you add a variable including dotenv-webpack to the top of your config file like so:

const Dotenv = require('dotenv-webpack');

Then within the plugins array you initialize Dotenv by doing the following:

plugins: [   new Dotenv()]

Once you have that set you need to create a .env file within the root of your project. When you have created that you can then place any variables within there that you need to use throughout your code like this:

VAR1=valueForVar1

Then within your React code you can use that environment variable like so:

process.env.VAR1

You should then be able to build your project using WebPack without any problems.

Here’s a full example of a webpack.config.js using dotenv-webpack:

I’m a front-end engineer who builds apps. http://www.craigstroman.com/