0

I want to access the value of an environment variable in my JS file. I tried using the process.end.VAR_NAME method but it renders it as undefined. I can see the variable and its value by writing the SET command in my terminal but somehow cannot get the already existing value into my project. Please note that I do not have to initialize my variable, i just need to use an existing one into my project directly. Also, my project is not based on create-react-app, so is dotenv a possibility to make this work?

1

1 Answer 1

1

process.env only works for nodeJS, that's why it renders as undefined with react.

I guess you use webpack, if so, you can use webpack.DefinePlugin, which is very usefull to pass environment variable.

You can use it like that:

{
    //...
    plugins: [
        new webpack.DefinePlugin({
            'MY_GLOBAL_VARIABLE': JSON.stringify(process.env.MY_GLOBAL_VARIABLE)
        })
    ]
    //...
}

Thanks to that, the variable 'MY_GLOBAL_VARIABLE' is global and can be accessed everywhere in your code.

You can try it by typing console.log(MY_GLOBAL_VARIABLE) where you want (in a js file sure).

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, I tried using that, but I still get it as undefined, do I need to add it in package.json and .eslintrc file as well?
Can you show me your webpack config please ? And the way you call your variable
Moreover, if you use eslint, you may need to set this config: "globals": { "ENV": false }
I tried using the above method, I still get it as undefined, and I am calling it in my component just as GLOBAL_VARIABLE_NAME
Can you still please give me your webpack configuration. It is a known solution, you may have forgotten something ^^.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.