Posts Learn Snippets Categories Tags About
/
How to set up sitemaps on NuxtJs application cover

How to set up sitemaps on NuxtJs application

Lear how to set up sitemap.xml file for your NuxtJS application and boost SEO

6 months ago

10 mins read

20 views

To ensure that search engines like Google and Bing index our site content, we have to have a sitemap file that essentially contains all of the links to the website. In order to do so in a NuxtJs application, we have to make use of nuxt/sitemap module.

Install the dependency
yarn add @nuxtjs/sitemap
Once it's installed now we have to configure the config in nuxt.config.js

Sitemap Configuration
Make sure to define the new sitemap config and do note the important part is the routes property. This route property can accept array and function and for this example, we are getting the routes from the backend server of our API. By default, the links to our application are generated by the module but it only works for non-dynamic links. For dynamic links, we will have to configure the routes property of the sitemap like below.

import axios from 'axios'

export default {
  sitemap: {
    gzip: true,
    routes: async () => {
      const { data } = await axios.get('https://your-website.test/get-sitemap-data')
      return data
    }
  }
}

By right the backend should return an array of links that are generated and the routes property in this case consume the links and generate the file. Below is the response for illustration, for a full tutorial there will be another separate post for it.
[
  'post/1',
  'post/2',
  'post/3',
]

Those links returned from the backend are only for the dynamic page so by right we have to generate all of the links that will be consumed by the sitemap module.
posts/_id.vue
categories/_id.vue

Generate sitemap
By now when you run "yarn generate && yarn start" you will be able to access the sitemap file through "localhost:3000/sitemap.xml" and the generated file will contain links as follows. For demonstration imagine postsrc.com as the URL.
postsrc.com (generated by sitemap module)
postsrc.com/posts (generated by sitemap module)
postsrc.com/posts/1 (generated by the backend api)
postsrc.com/posts/2 (generated by the backend api)
postsrc.com/posts/3 (generated by the backend api)