Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use dotenv in a react project?

I am trying to set some environment variables (for making API calls to dev/prod endpoints, keys depending on dev/prod, etc.) and I'm wondering if using dotenv will work.

I've installed dotenv, and I am using webpack.

My webpack entry is main.js, so in this file I've put require('dotenv').config()

Then, in my webpack config, I've put this:

  new webpack.EnvironmentPlugin([     'NODE_ENV',     '__DEV_BASE_URL__'  //base url for dev api endpoints   ]) 

However, it is still undefined. How can I do this correctly?

like image 645
user1354934 Avatar asked Feb 11 '17 23:02

user1354934


People also ask

Can I use dotenv in frontend?

Dotenv is wonderful. It allows you to use environment variables in your code, hence separating the code from its running environment.

Why we use dotenv in react?

Dotenv is commonly used (create-react-app uses it, so there) and will get the variables from our . env file and add them to the global process.


1 Answers

Sorry for picking up old question, but
react-scripts actually uses dotenv library under the hood.

With [email protected] and higher, you can work with environment variables this way:

  1. create .env file in the root of the project
  2. set environment variables starting with REACT_APP_ there
  3. access it by process.env.REACT_APP_... in components

.env

REACT_APP_BASE_URL=http://localhost:3000 

App.js

const BASE_URL = process.env.REACT_APP_BASE_URL; 

See docs for more details.

like image 191
Dmitry Demidovsky Avatar answered Oct 02 '22 02:10

Dmitry Demidovsky