Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

process.env on Client-Side ReactJS

I understand that process.env only work on server-side, I want to use the same concept but in client side because my app is deployed on aws s3, I know that we can put a variable in process.env from webpack how I can do the same but in client side?

like image 740
Emerson P. Ballen Avatar asked Apr 02 '18 18:04

Emerson P. Ballen


People also ask

Are env variables exposed to client?

Loaded env variables are also exposed to your client source code via import.meta.env as strings.

Can I use .env in react?

Today we will learn how to use . env file in our react js project. If you are using some external APIs for data you must use the . env file to store your sensitive credentials like API keys.

How do you write process env in react?

Using a .env fileconst { REACT_APP_MY_ENV } = process. env; Assuming the application was created with create-react-app, this will work out of the box, with no additional work. If the application was not created with create-react-app, add the dotenv package to the project.

Where do I put the .env react?

This is a quick tutorial on how to create and access environment variables in React with a dotenv ( . env ) file. React apps built with Create React App support dotenv environment variables out of the box, so all you need to do is add a . env file to the root folder of your React project.


1 Answers

You can use webpack.DefinePlugin to put variables in process.env. Below, most common example with React:

plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': '"production"'
    }
  })
]

isn't it enough?


I've created this example to prove that it works:

// webpack.config.js
const webpack = require('webpack');

module.exports = {
    entry: './index.js',
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': '"production"'
            }
        })
    ]
};

// index.js
console.log(process.env);

console.log(process.env.NODE_ENV);

and the output file of this configuration is like this:

// ... some internal webpack init function ... 
([function(e,n){console.log(Object({NODE_ENV:"production"})),console.log("production")}]);    

so as you may notice, values are replaced correctly.

If you need this variable you can do some initialization like:

global.myVar = process.env.NODE_ENV;

or something like this.

like image 118
Morishiri Avatar answered Sep 30 '22 08:09

Morishiri