How to use Heroku Environment Variables in React with Webpack

Webpack logo

Our team was working on a legacy project that used Webpack in a React app. When we first built it, the application had trouble retrieving our Heroku environment variables. So we (okay, I) had taken a shortcut and just hard-coded environment variables into the various Webpack files.

For example, here’s a snippet from

new webpack.DefinePlugin({
    'NODE_ENV': JSON.stringify('production'),
    'API_URL': JSON.stringify(''),
    'VIDEO_HELP_URL': JSON.stringify('')

Obviously this was not a good long-term solution, as it would require a code deployment any time an environment variable needed to be changed. As a general rule, a configuration change should not require a deployment.

When it was time to add a new variable, we decided to clean up the mess. The fix to have Heroku read the environment variables was actually quite simple: declare the variable, then wrap process.env.VARIABLE with JSON.stringify.

Here’s the new snippet:

new webpack.DefinePlugin({
    'NODE_ENV': JSON.stringify('production'),
    'API_URL': JSON.stringify(process.env.API_URL),
    'VIDEO_HELP_URL': JSON.stringify(process.env.VIDEO_HELP_URL)
Comedian pointing to his head with the caption "Ease peasy lemon squeezy". Heroku environment variables

One bit of technical debt knocked out nice and quick.

As an aside, there are some pretty strong opinions about Webpack out there. Here’s a funny thread on the topic.

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x