Search code examples
reactjsparameter-passingfetchcommand-line-arguments

How can I pass a custom server hostname using React?


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 use 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 file start.js I can access process.env.serverhost, but I want to be able to access the hostname in the browser for my actual fetch calls. I don't want to set the hostname in "config" in package.json file 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 hostname given as an argument in the command line in my source 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 source files, but when I tried to fetch(<URL>), I got a bunch of failure to parse URL errors.)

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


Solution

  • 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://create-react-app.dev/docs/adding-custom-environment-variables/#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