user11910832
user11910832

Reputation:

Environment variables - undefined

I want to use environment variables. I made a custom react app environment.

Everything is ok, the app runs properly, no errors. But the variables from .env file gives undefined and the process.env gives an empty object.

I added dotenv and REACT_APP prefix to the variable.

And in webpack.config.js file i added node: { fs: 'empty' }, from here

Here are my configurations.

Folder structure:

enter image description here

Upvotes: 4

Views: 5008

Answers (4)

user11910832
user11910832

Reputation:

PROBLEM SOLVED:

  1. Uninstall dotenv
  2. Remove these two from main app.js file:
const dotenv = require('dotenv')
dotenv.config();
  1. Remove the flag --env from npm start script.

  2. Remove node: { fs: 'empty' } from webpack.config.js file

  3. Install dotenv-webpack, and follow the instructions from there.

No need for REACT_APP prefix.

Fixed configuration files

Upvotes: 2

Tony
Tony

Reputation: 20092

You can use webpack.DefinePlugin

 plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('development')
            }
        })
    ],

Then in your code simply use process.env.NODE_ENV to access ENV variable

Upvotes: 0

Luthfi
Luthfi

Reputation: 394

You have to put REACT_APP in front of the variable name you want to have

eg:/

REACT_APP_YOUR_VAR="something"

You don't need to install Dotenv or something else, because React has its own.

Upvotes: 1

Harish
Harish

Reputation: 1911

try https://www.npmjs.com/package/dotenv to use .env variables

In your entry JS file add below code snippet (maybe your ./src/assets/js/app.js)

const dotenv = require('dotenv')
dotenv.config()

and restart your app.

Upvotes: 0

Related Questions