Home » vue » How to specify different API urls in vue.js for my computer, coworker's computer, and production?

How to specify different API urls in vue.js for my computer, coworker's computer, and production?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’d like to have the URL to my api / backend server automatically be loaded and used in all the requests that my vue.js application makes.

For my own laptop, I’m usually running the backend at localhost, so I’d like the url to be localhost.

But on production, and on my coworker’s computer, I’d like the production URL to be used (or a staging URL for coworker’s computer).

This is because coworker isn’t running the backend locally.

Can this be achieved with vue.js?

Answers:

Check environment variables and modes for vue cli 3; Essentially set up two .env files for development and production separately (.env.development and .env.production):

In .env.development, where each developer can set up the base url differently:

VUE_APP_BASE_URI=localhost:8000 or a staging uri for your coworker

In .env.production:

VUE_APP_BASE_URI=YourProductionURL

And in your app, configure the http request to use process.env.VUE_APP_BASE_URI as the base URL.

And now when you and your coworker are in the development mode (i.e. running npm run serve), it will pick the VUE_APP_BASE_URI from .env.development; And when it’s deployed to production via npm run build, your app will use VUE_APP_BASE_URI from .env.production file.