ReactJs How to pass custom server hostname?

12,089

You can have .env file per environment and then set

REACT_APP_API_ENDPOINT=http://localhost.whatever

So for example .env.development

REACT_APP_API_ENDPOINT=http://localhost.whatever

.env.production

REACT_APP_API_ENDPOINT=http://production.whatever

Usage of env variables is explained here https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#what-other-env-files-can-be-used

Eventually, you can add it to your script like

"scripts" : {
   "start": "REACT_APP_API_ENDPOINT=http://localhost.whatever npm/yarn start"
   "start-production": "REACT_APP_API_ENDPOINT=http://production.whatever npm/yarn start"
}

If you don't really want to use above approaches at all then, assign your ip to some variable and add it to command to run your app

"scripts" : {
   "start": "REACT_APP_API_ENDPOINT=$(curl ifconfig.me) npm/yarn start"
   "start-other: "REACT_APP_API_ENDPOINT=$(echo MY_VAR_WITH_IP) npm/yarn start"
}

And then access your url from process.env.REACT_APP_API_ENDPOINT

Share:
12,089
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin about 2 years

    I want to be able to pass a custom server hostname when running my react app to be used in the url when I need to fetch data. The server is currently running on my local computer, so when I fetch(url) I've been using "http://localhost:...." which has worked perfectly. But I want to be able to have to pass a custom host name, such as my ip address, to be used in the url (i.e. http://ipaddress:...).

    I've tried starting my app like this:

    serverhost=ipaddress npm start
    

    and then in my package.json file

    "scripts" : {
       "start": "react-scripts start $serverhost"
    }
    

    and in start.js I can access process.env.serverhost, but I want to be able to access the host name in the browser for my actual fetch calls. I don't want to set the hostname in "config" in package.json or in an .env file because it has to be able to change (I'm under the impression that this isn't possible). I just want to be able to access the server host name given as an argument in the command line in my src files.

    (I read somewhere about doing

    REACT_APP_MY_VAR=test npm start 
    

    and then accessing it as

    process.env.REACT_APP_MY_VAR
    

    in the src files but when I tried to fetch(url) I got a bunch of failure to parse URL errors)

    EDIT: I tried using REACT_APP variables and I no longer got parsing URL errors when fetching