score:3

Accepted answer

from the docs: https://create-react-app.dev/docs/proxying-api-requests-in-development/

keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that urls like /api/todos point to the right thing in production.

as an alternative, you can use environment variables instead: https://create-react-app.dev/docs/adding-custom-environment-variables/

you should create .env.development and .env.production files at the root of your project:

# .env.development

react_app_proxy=http://localhost:9090
# .env.production
react_app_proxy=<some other domain>

and consume it on the react app:

// anywhere in the react app
const react_app_proxy = process.env.react_app_proxy

score:0

the proxy value in package.json is static and there is no possible way to retrieve its value from the environment variables. so just use the dynamic way for the proxy registration like described here: https://create-react-app.dev/docs/proxying-api-requests-in-development/#configuring-the-proxy-manually it will allow you to retrieve any environment variable with the syntax process.env.some_name

example:

const { createproxymiddleware } = require('http-proxy-middleware')
module.exports = function(app) {
  app.use(createproxymiddleware('/api', {
      target: process.env.backend_url,
      changeorigin: true,
    })
  );
};

now i have answered your primary question, i think this is an xy problem. when running a react application on a remote environment, there should be a reverse proxy (e.g: nginx, apache, ...) in charge of redirecting frontend requests (assets and routes) on the statically served react files, and the backend requests on the backend. the rule to implement is the following:

  • if the incoming requests corresponds to a predefined pattern (e.g: /api/...), forward to the internal url of the backend
  • else, if the request corresponds to a file from react's build, serve it
  • else, assert it's a route, then serve index.html

the react's web server should be used on development machines only. it provides real-time compilation and live reload, which is of no use on a production environment, and it's probably not tested against security vulnerabilities. it's still not a bad idea to load the backend's url from environment variables, as it allows your code base to remain the same for every developer working on your project.


Related Query

More Query from same tag