Back to blog

How to Create Sitemaps for a Nuxt 3 Static Site

·2 min read
NuxtVueSEO

I run a Minecraft server analytics platform which uses Nuxt 3 for its website, with the Nuxt Content module powering blogs and documentation via markdown files. This works well, but without a sitemap, a portion of my website wasn't being indexed by search engines - a problem for discoverability.

Since Nuxt 3 and its content module were in beta at the time, other sitemap libraries hadn't yet been updated to support them. I had to create a temporary solution and wanted to share it in case it helps others.

Installation

First, install the sitemap library:

yarn add sitemap

Next, create a server folder in your site's root directory with a routes sub-folder inside it. Then create the sitemap file:

server/routes/sitemap.xml.ts
import {serverQueryContent} from '#content/server';
import {SitemapStream, streamToPromise} from 'sitemap';
 
export default defineEventHandler(async (event) => {
    const articles = await serverQueryContent(event).find();
 
    const sitemap = new SitemapStream({ hostname: 'https://yourpageurl.com' });
 
    // Root page
    sitemap.write({ url: '/' });
 
    // Other static pages
    sitemap.write({ url: '/example/page-1' });
    sitemap.write({ url: '/example/page-2' });
 
    // Nuxt content pages
    articles.forEach((article) => sitemap.write({ url: article._path, changefreq: 'monthly' }));
    sitemap.end();
 
    return (await streamToPromise(sitemap));
});

Here we're generating a sitemap based on static pages and fetching dynamic pages from the Nuxt Content module. Static pages like pages/test/hello-world.vue need to be entered as /test/hello-world in the sitemap, while dynamic pages like /blog/post-1 are automatically added if created via Nuxt Content.

Creating for Static Sites

If you're using static generation, these routes won't exist upon deployment. Nuxt lets us pre-render these pages, building the sitemap during the build process. Add the following to your nuxt.config file:

nuxt.config.ts
import { defineNuxtConfig } from 'nuxt'
 
export default defineNuxtConfig({
    nitro: {
        preset: 'aws-lambda',
        prerender: {
            routes: ['/sitemap.xml']
        }
    }
})

That's it - you've created a sitemap for your statically generated Nuxt 3 application. You can preview it at https://yourpageurl.com/sitemap.xml once deployed.