How to generate Sitemap in NuxtJS project

Last updated at April 19, 2021

💬

Install @nuxtjs/sitemap package

bash
npm install @nuxtjs/sitemap --save

Create route generation utility file

Create createRoute.js file in /utils folder. /utils folder is not default folder by NuxtJS. So you can create it by manual.

Than add source code like bellow. This source code is from NuxtJS Content Official Documentation.

/utils/createRoute.js
export default async () => {
  const { $content } = require('@nuxt/content')
  const files = await $content({ deep: true }).only(['path']).fetch()

  return files.map((file) => (file.path === '/index' ? '/' : file.path))
}

Import createRoute.js and configure sitemap in nuxt.config.js

Import createRoute.js file at the top of the nuxt.config.js file

/nuxt.config.js
import createRoutes from "./utils/createRoutes"

export default {
  // ...
}

Add @nuxtjs/sitemap to modules

/nuxt.config.js
export default {
  // ...

  modules: [
    '@nuxt/content',
    '@nuxtjs/sitemap',
  ],

  // ...
}

Configure sitemap

/nuxt.config.js
export default {

  // ...

  sitemap: {
    hostname: process.env.BASE_URL,
    gzip: true,
    routes() {
      return createRoutes();
    }
  }

  // ...
}