How to Add a Sitemap to Nuxt
As I am building Web Developer's Journal, I am using more of the awesome community modules that make the dev experience incredibe. This time I take a look at how to add an XML sitemap to Nuxt.
Install
The module is available at https://github.com/nuxt-community/sitemap-module
. Let's install it:
npm i @nuxtjs/sitemap
Configuration
Then add it to nuxt.config.js
:
modules: [
...
sitemap() {
return {
hostname: "https://webdevelopersjournal.com",
exclude: ["terms-privacy/", "contact/", "courses/"],
cacheTime: 1000 * 60 * 60 * 2,
trailingSlash: true,
gzip: true,
routes: createSitemapRoutes
}
]
For static and SSR deployments, you must add a hostname
.
cacheTime
tells how often should the sitemap be regenerated. Doesn't really add any value with static deployment (as in my case).
I am using trailingSlash
on WDJ, so I set it to true in the sitemap too.
I also enabled gzip
for smaller transfer size.
routes
property
The The routes
property is probably the most complex. It can be an array or a function. You can use an array wehen you manually set the routes. By default it uses the same setting as you have in nuxt.generate. I don't have anything there. I rather created a custom function based on the guide here.
const createSitemapRoutes = async () => {
let routes = [];
const { $content } = require("@nuxt/content");
const posts = await $content("articles")
.only(["slug", "createdAt"])
.fetch();
for (const post of posts) {
routes.push({
url: `/${post.slug}`,
changefreq: "monthly",
lastmod: new Date(post.createdAt)
});
}
return routes;
};
export default createSitemapRoutes;
I could be more sophisticated with the changefreq, but in this case it doesn't make much difference. I don't plan to update my posts too often. And I have given one week to push out a minimalistic blog so I don't want to prematurely optimize.
You need to import this function into nuxt.config.js
and you are done.
It would be pretty easy to refactor this to use an API instead of Nuxt Content, but I leave that to you for now.