Solved: get base url vuejs

Sure, Here you go,

In programming, it’s crucial to understand what base URL is; it’s the root of where all the routes of our application reside. In Vue.js, one of the most popular JavaScript frameworks, this idea becomes particularly important when routing. In this article, we’ll focus on how to get base URL in Vue.js.

Vue.js is a progressive JavaScript Framework that is approachable for users. Although it’s incredibly powerful for building single-page applications, developers often face some challenges. One of these may be getting the base URL.

let baseUrl =;
let protocol = window.location.protocol;

Understanding the Above Code

In the JavaScript code snippet above, we’re essentially calling the host and protocol properties of the window.location object. This object is quite useful as it can be used to get the current page address (URL) and to redirect the browser to a new page.

The returns the hostname (domain name) and port (if there is one) of a web page, and the window.location.protocol returns the web protocol used (http:// or https://). Combine these two, and you have your base URL.

Detailed Breakdown of the Code

The window object represents an open window in a browser. It is automatically created by the browser on page load. The window.location or simply location object can be used to get information about the current page address(URL) and to redirect the browser to a new page.

let baseUrl = protocol + "//" + baseUrl;

Here, we are concatenating the protocol (which we have gotten using window.location.protocol), two slashes, and baseUrl (which we got using together to form our base URL in Vue.js.

Related Libraries and Functions

Vue Router is the official router for Vue.js. It works with the Vue.js ecosystem perfectly well and makes building single-page applications with Vue.js a breeze. Vue Router has a base property in its constructor where you can set the base URL for all routes.

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,

Again, using process.env.BASE_URL, you can set the base URL for your application in a more abstract way if you’re already using Vue Router.


In this article, we delved into the concept of a base URL, why it is needed, and how it can be obtained in a Vue.js application. We also looked into the Vue Router and how to use it to setup the base URL. These solutions are especially handy when dealing with single-page applications in the Vue.js framework.

With these in your toolkit, you should now be better equipped to handle base URL related problems in Vue.js! Whether you’re working on a brand new project or maintaining some legacy code, remember – understanding the basics of your tools will always give you an edge.

Related posts:

Leave a Comment