title |
---|
Sitemaps |
A sitemap file is useful for helping Google to better index your website, ensuring that the content you write can be visible on search results.
This can be created utilising the sitemap
library, so you'll need to install that which can be done like so:
yarn add sitemap
We will be utilising the server routes available within Nuxt 3, and to do so you'll need to create the server/
folder within your websites root directly.
Once this is done, create a routes/
folder inside this, and add a sitemap.xml.ts
file, this corresponds to https://example.com/sitemap.xml
.
You'll need to add the following:
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://example.com' });
articles.forEach((article) => sitemap.write({ url: article._path, changefreq: 'monthly' }));
sitemap.end();
let data = await streamToPromise(sitemap);
return data;
});
Now, once users go to https://example.com/sitemap.xml
, you'll find the generated XML file with all your blog posts.