C
C
cester2020-07-07 13:16:09
JavaScript
cester, 2020-07-07 13:16:09

How to correctly form api url on the frontend?

Good afternoon! Interesting opinion of experienced people.
How is it more correct to set api url on the frontend , relative to the domain, or set a variable in packege.json and then form api url relative to it in the code ?
For example, two options:
1. In code

const getApiUrl = () => {
      if (document.domain === 'staging.com') {
        return 'http://staging-api.com';
      } else if (document.domain === 'prod.com') {
        return 'http://prod-api.com';
      }
      return 'http://dev-api.com';
    };


2. In package.json
"buid:staging" "cross-env --env.API_VARIABLE=staging",
....


Further in the code
const apiUrl = {
staging: 'http://staging-api.com',
prod: '...'
dev: '...'
}


I would be grateful for any article on this topic or strong arguments, a discussion with the backender)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2020-07-07
@cester

"buid:staging" "cross-env --env.API_ENDPOINT=https://staging-api.com",

Further in the code
// apiClient.js
function apiCall(method) {
    return fetch(API_ENDPOINT + method)
}

// main.js
apiCall('/some/api/method')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question