How To Add DotEnv To Webpack

How To Add DotEnv To Webpack

Colin Stodd
20 Mar 2018 (Published)
27 Mar 2020 (Updated)

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.

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

     npm install dotenv-webpack --save
  2. 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';
  3. Now make sure to add .env to your .gitignore file so that it doesn’t get deployed to Git.

     # .gitignore
     .env # Add to .gitignore file
  4. Then add this plugin to your webpack.config.js file.

     // webpack.config.js
     const Dotenv = require('dotenv-webpack');
     module.exports = {
       plugins: [
         new Dotenv()
       There seems to be a bug with either fs or dotenv-webpack that gives you this error:
    Error: Can't resolve 'fs' in. Nevertheless, I've included the work-around below.

    (Work-around): Also include this to your webpack.config.js file if getting the aforementioned error:

     module.exports = {
         // Add
         node: {
           fs: 'empty'
  5. In your main project folder ie index.js, add this line of code to require dotenv.

     require('dotenv').config(); // See Blurb/Alert above
  6. And you can test to see that it’s working by logging it to your console like so:


Please let me know in the comments that everything is working for you guys. I noticed the up-votes on the first comment that it wasn’t working, but I think I found the culprit and posted the fix above, but to be certain I’d appreciate it if you could let me know…