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 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({ 'process.env':{ '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') } })

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({ 'process.env':{ 'NODE_ENV': JSON.stringify('production'), 'API_URL': JSON.stringify(process.env.API_URL), 'VIDEO_HELP_URL': JSON.stringify(process.env.VIDEO_HELP_URL) } })
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 vote
Article Rating
Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x