'How to setup the url of the backend site on react build for production

When the site is running on the development way, "npm start", the backend url used is from the proxy at the package.json.

When i go for the production way "npm build", the backend url is not used from package.json, because that proxy is only for development.

I would like some help to understant how to configure that backend url, i am using the same url for both development and production.

In the configuration file .package.json:

{
  "name": "mysite_frontend_v1",
  "version": "0.1.0",
  "private": true,
  "proxy": "https://api.minhaholding.com",
...
} 

And then created a file .env :

REACT_APP_API_URI = 'https://api.mysite.com'

the api.js file :

function request(path, { data = null, token = null, method = 'GET' }) {
  return fetch(path, {
    method,
    headers: {
      Authorization: token ? `Token ${token}` : '',
      'Content-Type': 'application/json',
    },
    body: method !== 'GET' && method !== 'DELETE' ? JSON.stringify(data) : null,
  })
    .then((response) => {
      // If it is success
      if (response.ok) {
        if (method === 'DELETE') {
          // If delete, nothing return
          return true;
        }
        return response.json();
      }

      // Otherwise, if there are errors
      return response
        .json()
        .then((json) => {
          // Handle JSON error, response by the server
          if (response.status === 400) {
            const errors = Object.keys(json).map((k) => `${json[k].join(' ')}`);
            throw new Error(errors.join(' '));
          }
          throw new Error(JSON.stringify(json));
        })
        .catch((e) => {
          throw new Error(e);
        });
    })
    .catch((e) => {
      // Handle all errors
      toast(e.message, { type: 'error' });
    });
}

export function signIn(username, password) {
  return request('/auth/token/login/', {
    data: { username, password },
    method: 'POST',
  });
}

export function register(username, password) {
  return request('/auth/users/', {
    data: { username, password },
    method: 'POST',
  });
}


Solution 1:[1]

The proxy feature isn't meant for production. So, you must set host URL in .env file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Masoud