Recently i tried to solve the following problem: how to get react app to get backend Url from environment variable.
The embarrassing truth is that until now my code was full of statements like this:
fetch('http://localhost:8000/login', {
method: "POST",
credentials: 'include',
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify( data )
})
As you may notice - the url is hardcoded. The problem here is that this code will run only at developer environment where server running on 127.0.0.1 ("localhost") ip. But what about production environment where backend url can be http://yourappname.herokuapp.com ?
DONTENV
It appears the very cool solution for this problem is to use
dotenv node plugin. Using it give us ability to define all environment specific variables in .nev file:
REACT_APP_API_HOST=http://localhost:8000
Now inside your react code you can access this variable this way:
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
};
fetch(`${process.env.REACT_APP_API_HOST}/login`, requestOptions)
.then(handleResponse)
CREATE REACT APP
Create react app tool supports using .env files (so there is no need to install dotenv). You can create different .env files for different environments: like
.env.local and
.env.production.
By default - the "serve"(npm start) task will use "local", while "build" (npm run build) - will use production...
Cool!