How To Add DotEnv To Webpack

How To Add DotEnv To Webpack

Colin Stodd
20 Mar 2018 (Published)

dotenv allows you to store sensitive data variables locally (Secret Keys, etc), without having to include them directly in your app files.

This is based off of dotenv-webpack’s NPM package.

You first want to install dotenv-webpack via your terminal:

npm install dotenv-webpack --save

Then create a file in the root of your directory .env and add your secret keys or whatever it is you want to hide like this.

SECRET_KEY_EXAMPLE = '3213213232132132123132adassdasdsd';

Now make sure to add .env to your .gitignore file so that it doesn’t get deployed to Git.

Then add this plugin to your webpack.config.js file.

// webpack.config.js
const Dotenv = require('dotenv-webpack');
module.exports = {
  plugins: [
    new Dotenv()

In your main project folder ie index.js, add this line of code to require dotenv.


And you can test to see that it’s working by logging it to your console like so: