See all posts

Simple Sitemap For Vue Router

January 7, 2019
2 min

A client wanted me to send her all the links for an app which uses Vue with Vue Router. At first, I tried to compose the list by hand – the app has only 45 links. But after a while decided it would be easier to do it with Javascript. And even more useful if I get the same request in the future.

In my case, I only needed a simple list of all the links to send to the client. I then also decided to expand my solution to output the list in sitemap XML format.

Note that the below solutions are for simple use cases like mine. If you need a real sitemap, I recommend installing an NPM package like vue-router-sitemap.

Simple List

The getRoutesList function below returns an array with all the routes for your app:

const router = new Router({ /* Your Router config go here */ });

function getRoutesList(routes, pre) {
  return routes.reduce((array, route) => {
    const path = `${pre}${route.path}`;

    if (route.path !== '*') {

    if (route.children) {
      array.push(...getRoutesList(route.children, `${path}/`));

    return array;
  }, []);

getRoutesList(router.options.routes, '');

Example output:


The first parameter of the getRoutesList function requires the options.routes array that is available on the Router instance. The second is the URL prefix for all the routes.

For my use case I placed the code inside my router file (router/index.js) and used console.log around the function call to display the routes.

If you want to use the function inside a component (eg. inside mounted), change the first parameter to this.$router.options.routes.

XML Format

The getRoutesList can also be used to also generate XML sitemap format:

function getRoutesXML() {
  const list = getRoutesList(router.options.routes, '')
    .map(route => `<url><loc>${route}</loc></url>`)
  return `<urlset xmlns="" xmlns:xsi="" xsi:schemaLocation="">


The getRoutesXML uses the previous function and makes modifications to its output. It wraps all the routes in <url><loc> tags by using the map array method. Then by using join, it converts the array to a string with each route on its own line.

The function’s return statement includes the <urlset> with all the required attributes for sitemap XML format.

Previous Adding a custom loader in a Vue CLI app Next Empty An Array Without Losing Reference