Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS: Use environment variables to specify two API urls based on production vs development

I used create-react-app as the boilerplate for my React app.

I am using fetch to make a request to my local server

fetch("http://localhost:3000/users")
 .then(function(res){
  return res.json()
})
.then(function(res){
  return res.data
})

Eventually when I deploy to heroku I won't be using http://localhost but rather something like https://safe-escarpment-99271.herokuapp.com/.

Is there a way to store the API url in an environment variable

ie. fetch(API_URL)

so I can have it on Github when it's deployed but still test locally and not have to change the url back and forth.

I see

new webpack.DefinePlugin({
  'process.env':{
     'NODE_ENV': JSON.stringify('production'),
     'API_URL': JSON.stringify('http://localhost:8080/bands')
   }
}),

on many answers but that doesn't seem to be working for me. When I console.log(process.env) the only thing that shows is NODE_ENV and PUBLIC_URL

like image 250
T. Marren Avatar asked Dec 30 '16 01:12

T. Marren


2 Answers

Maybe this will work for you:

const url = (process.env.NODE_ENV === 'development') 
    ? 'http://localhost:8080/bands/'
    : 'https://<your-app>.herokuapp.com/bands/';

On heroku default NODE_ENV=production: https://devcenter.heroku.com/changelog-items/688

like image 62
Jarosław Wojciechowski Avatar answered Sep 22 '22 22:09

Jarosław Wojciechowski


Try using EnvironmentPlugin:

new webpack.EnvironmentPlugin([
    "NODE_ENV",
    "API_URL"
])
like image 40
Andrés Andrade Avatar answered Sep 21 '22 22:09

Andrés Andrade