Search code examples
javascriptreactjspowershellenvironment-variablesdotenv

.env variable returns undefined in React JS app


I am working on this react app and thinking of adding some environment variables inside, this is what I've done:

  1. installed the latest version of react-scripts
  2. added .env file on the root folder (the same location where node_modules folder is)
  3. added REACT_APP_OTHER_OTHER_THING=asdfas just to test the variable
REACT_APP_OTHER_OTHER_THING=asdfas
  1. open index.js and console.log(process.env.REACT_APP_OTHER_OTHER_THING) inside to see the output
import React from 'react';
import Reactdom from 'react-dom';
import App from './App';

console.log(process.env.REACT_APP_OTHER_OTHER_THING, 'DOTENV')

Reactdom.render(<App/>, document.getElementById("app"))

then I rebuilt the app and started the app to see the result but then it gives out undefined as the output for process.env.REACT_APP_OTHER_OTHER_THING. I then tried to print process.env.NODE_ENV (which is working and prints "development" as output).

note: I have also tried to add temporary variable as the docs said in https://create-react-app.dev/docs/adding-custom-environment-variables >> rebuilt the server and run ($env:REACT_APP_OTHER_OTHER_THING= "abcdef") -and (npm start) << due to me running it on powershell which still gives undefined as output.

is there anything I can do on this? thank you


Solution

  • Alright, the problem I'm having seemed to be from the webpack I made in my React App,

    I tried to follow the instruction from this article and it's working well!

    after configuring my webpack, I rebuilt it, restart the server, and it works!

    edit: for my solution, I added:

    const dotenv = require('dotenv');
    
    const env = dotenv.config().parsed;
    
    const envKeys = Object.keys(env).reduce((prev, next) => {
        prev[`process.env.${next}`] = JSON.stringify(env[next]);
        return prev; }, {});
    

    at the top of webpack.common.js

    and also added

        plugins: [
            new webpack.DefinePlugin(envKeys), //this line
        ]
    

    in the module.exports in the plugin. I hope this helps! :)