Zack Shapiro
Zack Shapiro

Reputation: 6998

Using dotenv module with React

I have dotenv in my dependencies of my app. Following the directions, I have a .env file and inside is NODE_ENV=development.

In my main.js file, I'm running a simple require('dotenv').config(); and yet when I access process.env, I'd expect an object and I get {}

What am I doing wrong here? Thanks

Upvotes: 1

Views: 1325

Answers (1)

Ijas Ameenudeen
Ijas Ameenudeen

Reputation: 9259

dotenv only works in the server-side. To use .env in the client side with webpack, use dotenv-webpack.

  1. Install the package, yarn add dotenv-webpack -D OR npm install dotenv-webpack --save
  2. Add it to your Webpack config file.

    // webpack.config.js 
    const Dotenv = require('dotenv-webpack');
    module.exports = {
      ...
      plugins: [
        new Dotenv({
          path: './.env', // Path to .env file (this is the default) 
          safe: true // load .env.example (defaults to "false" which does not use dotenv-safe) 
        })
      ]
      ...
    };
  3. Add .env to your .gitignore file

NOTE: Your .env files can include sensitive information. Because of this, dotenv-webpack will only expose environment variables that are explicily referenced in your code to your final bundle.

Upvotes: 2

Related Questions