Skip to content

Instantly share code, notes, and snippets.

Last active Oct 20, 2021
What would you like to do?
Sitemap nextjs code
// import functions from the package
import { SitemapStream, streamToPromise } from "sitemap";
// Fetch data from a source which will be used to render the sitemap.
const { posts } = await graphlqlFetch(`
⁠ query getSitemapData {
⁠ projects: allWorks {
⁠ slug {
⁠ current
⁠ }
⁠ publishedAt
⁠ }
⁠ }
⁠ `);
// Create the a stream to write to with a hostname which will be used for all links
// Your are able to add more settings to the stream. I recommend to look a the npm package for more information.
const smStream = new SitemapStream({
hostname: "",
// Add frontpage
url: "/",
// Add a static url to ex: about page
url: "/about",
// add all dynamic url to the sitemap which is fetched from a source.
posts.forEach((element) => {
url: `/${element.slug.current}`,
lastmod: element.publishedAt,
// tell sitemap that there is nothing more to add to the sitemap
// generate a sitemap and add the XML feed to a url which will be used later on.
const sitemap = await streamToPromise(smStream).then((sm) => sm.toString());
export default async (req, res) => {
// here is the generation of the sitemap happening
// tell the output that we will output XML
res.setHeader("Content-Type", "text/xml");
// write the generate sitemap to the output
// end and send the data to the user or service.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment