Where and how to store API endpoints in vue js?

Nika Kurashvili picture Nika Kurashvili · Nov 15, 2018 · Viewed 7.7k times · Source

I am using vue-cli for front-end and lumen for back-end and I am curious about what is a best practice to store API root-url and endpoints in vue ?

Now I have constants.js file in src directory where API root-url and endpoints are like that:

const BASE_URL = "http://localhost:8000"

export const AddLanguge = BASE_URL + "/api/languages"

and when I need for example to implement add language functionality in component I import required API endpoint from constants.js like that:

import { AddLanguge } from '@/constants'

and then use axios to make request

this.$http.post(AddLanguge, params).then(response => {
   if (response.status == 200) {
       this.addLanguage(response.data.data)
   } else {
       this.setHttpResponseDialog(response)
   }
}).catch(er => {
       this.setHttpResponseDialog("Error")
})

I searched this question, but there is no clear answer some say: it's ok.

Others say: it's bad you must store that kind of data in dev.env.js and prod.env.js, and most important fact here is I don't get why are they saying so, why is it important to save that data in .env files? Or maybe is there some other better way?

Can you guys provide a right answer with good explanation or if there is no right answer and it depends on situation how can I decide which way is suitable for my case?

Answer

artoju picture artoju · Nov 15, 2018

.env files are recommended because you may have different endpoints depending on environment, that is to say are you running dev server with "npm run serve" or building for production with "npm run build". With .env config files they become environment variables and you don't need to hard code them into your app, it's just the most practical thing to do. With Vue CLI 3 you would have

//.env.development 
VUE_APP_BASEURL = "http://localhost:8000"

And in your app you could access it with.

process.env.VUE_APP_BASEURL

What I use to do is just have the base in a variable and then concatenate rest.

const BASE_URL = process.env.VUE_APP_BASEURL

this.$http.post(BASE_URL + '/api/languages/', params)