1 min read

Webpack way of using dynamic api endpoints based on environment

When working with the front-end, sometimes we need to use some sort of backend API. There may be at least two API servers – one for development and the other for production.

While developing frontend, I prefer to use the development server for the API rather than production and it makes sense. But, after finishing the frontend, the API endpoint URL should be changed to the production API server. So how do you keep track of whether your environment is development or production?

Here is my solution. If you are using webpack, then certainly you can use this solution. If you are not then definitely you should try webpack. I am sure you are gonna love it.

First, create a new js file that holds all the API endpoint URLs. For example apiendpoint.js, then paste the following code. Remember to change your actual URLs of yours.

const IS_LOCAL = process.env.NODE_ENV !== 'production'

const API_BASE_URL = IS_LOCAL ? 'http://awriter.dev/api' : 'http://awriter.com/api'

const LOGIN_URL = 'auth/login'
const ALL_ITEM_URL = 'itemdb/all'
const ADD_ITEM_URL = 'itemdb/additem'
const DELETE_ITEM_URL = 'itemdb/deleteitem'

export default {
  IS_LOCAL, API_BASE_URL, LOGIN_URL, ALL_ITEM_URL, ADD_ITEM_URL, DELETE_ITEM_URL
}

In this code, there is a constant named IS_LOCAL which detects the webpack environment. Then another constant is API_BASE_URL and assigns the base URL based on the environment. Then all the URLs are assigned with constant variables. At last, export all the constants for use within the external script.

Now assume that we need to use the login endpoint in the login component. we need to import the apiendpoint.js

import apiendpoint from '../apiendpoint'

Then all the constants will be available as a property of the apiendpoint.js and we can use the apiendpoint.LOGIN_URL in the HTTP request. I am using the Vue resource library for this. So I can set the HTTP root option to our base API URL by the following. Of course, you can set it with any HTTP library like Axios or jquery ajax.

Vue.http.options.root = apiendpoint.API_BASE_URL

And then in the login component,

this.$http.post(apiendpoint.LOGIN_URL, data).then(response => {
        console.log(response)
      }, error => {
        // console.log(error)
      })

That’s all. When we are in dev mode, the dev API will be used and after the build, it will use the API of the production server.