0

Here is the way in which I set up different API URL based on the current environment:

Development and Production, on npm, commanded setup env.

Is there are some more elegant solution cus my URLs are long:

Package.json

"scripts": {
    "start": "REACT_APP_BASE_URL=http://test-dev-1323211.us-east-1.elb.amazonaws.com/api/3.0 react-scripts start",
    "build": "REACT_APP_BASE_URL=http://test-1323211.us-east-1.elb.amazonaws.com/api/3.0 react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "prepare": "husky install",
 
  },
Mark James
  • 338
  • 4
  • 15
  • 43
  • Possible duplicate: [Detecting production vs. development React at runtime](https://stackoverflow.com/questions/35469836/detecting-production-vs-development-react-at-runtime) –  Apr 16 '21 at 11:39
  • [How to setup the env variable for the react app?](https://stackoverflow.com/a/66365372/2873538) – Ajeet Shah Apr 16 '21 at 16:33

1 Answers1

1

You can use .env files using dotenv library. See: https://create-react-app.dev/docs/adding-custom-environment-variables

EDIT:

From the docs

Adding Development Environment Variables In .env

To define permanent environment variables, create a file called .env in the root of your project:

REACT_APP_NOT_SECRET_CODE=abcdef

Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.


You can read more at the CRA docs or at DotEnv docs.

Solution

Basically you can use .env and .env.development.local to separate the URLs.

.env:

REACT_APP_BASE_URL=http://test-1323211.us-east-1.elb.amazonaws.com/api/3.0

.env.development.local:

REACT_APP_BASE_URL=http://test-dev-1323211.us-east-1.elb.amazonaws.com/api/3.0
Itamar
  • 1,601
  • 1
  • 10
  • 23
  • 1
    Linking elsewhere is not a sufficient answer; if you are sure this question isn't a duplicate, please include the relevant information in your answer. –  Apr 16 '21 at 11:40