Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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.mysite.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',
  });
}
like image 673
Diogo Wernik Avatar asked Oct 20 '25 07:10

Diogo Wernik


1 Answers

I don't know if that was the best solution, if someone finde a better one i would be glad with that.

So i started deleting the proxy:

{
  "name": "mysite_frontend_v1",
  "version": "0.1.0",
  "private": true,

} 

And then keep the .env file :

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

added a const in the api.js file :

const base_url = process.env.REACT_APP_API_URI

function request(path, { data = null, token = null, method = 'GET' }) {
  return fetch( base_url + 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',
  });
}

...

but than i started to get issues with CORS, so it was needed to make changes in the backend, that was in django.

So i followed this answer for the CORS configuration.

How can I enable CORS on Django REST Framework

After that, all was working ok, both production and development, not using proxy any more in that case.

like image 154
Diogo Wernik Avatar answered Oct 21 '25 20:10

Diogo Wernik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!