Webpack Set API Keys Depending On Environment

Let’s say that you have two sets of API keys. One for your development environment with no restrictions and one for your production environment with restrictions. When you’re ready to push your code to production, you need webpack to build your script with the production API key without exposing the development API key. Here’s how to achieve that.

In package.json add:

"scripts": {
"build-development": "webpack --env.build development",
"build-watch-development": "webpack --env.build development --watch",
"build-production": "webpack --env.build production --optimize-minimize"

Install webpack-env-loader.

npm i webpack-env-loader --save-dev

In webpack.config.js add:

loader: {
appSettings: {
name: 'app',
env: process.env.build

Create settings.js in the same directory as package.json.

module.exports = {
'app': {
'development': {
'api_key': '<your_api_key_here>'
'production': {
'api_key': '<your_api_key_here>'

In your project, add this line:

var settings = require('webpack-env-loader!../settings.js');

You can reference your API key using settings.api_key.

To build your project, run either of these commands:

npm run build-development
npm run build-production