Heroku Environment Variables in React with Webpack

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 the values of environment variables set in Heroku, where we had it deployed. 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 webpack.prod.js:

new webpack.DefinePlugin({
    'NODE_ENV': JSON.stringify('production'),
    'API_URL': JSON.stringify('https://www.ourcoolapp.com/api/v1'),
    'VIDEO_HELP_URL': JSON.stringify('https://www.youtube.com/watch?v=JKx_BTj_-IE')
})Code language: JavaScript (javascript)

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)
})Code language: JavaScript (javascript)
Easy peasy lemon squeezy meme

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.

Related Articles

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