Webpack way of using dynamic api endpoints based on environment

When working with the frontend, sometimes you need to use some sort of backend api. There may be two api server – one for development and other for production. While developing frontend, I prefer to use development server for the api rather that production and it makes sense. But, after finishing the frontend, api endpoint url should be changed to production api server. So how do you keep track 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 yo are gonna love it.

First, create a new js file which holds all the api endpoint url. For example apiendpoint.js, then paste the following code. Remember to change the 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 {

In this code, there is a constant named IS_LOCAL which detects the webpack environment. Then another constant is API_BASE_URL and assign the base url based on environment. Then all the urls are assigned with constant variables. At last, exporting all the constant for use within external script.

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

import apiendpoint from '../apiendpoint'

Then all the constant will be available as a property of the apiendpoint and we can use the apiendpoint.LOGIN_URL in the http request. I am using 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 => {
      }, error => {
        // console.log(error)

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


Leave a Reply