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