Skip to content

Instantly share code, notes, and snippets.

@emilpriver
Last active October 20, 2021 15:41
Show Gist options
  • Save emilpriver/475ab666d3155f84f9739cbf8567e640 to your computer and use it in GitHub Desktop.
Save emilpriver/475ab666d3155f84f9739cbf8567e640 to your computer and use it in GitHub Desktop.
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: "https://priver.dev",
⁠});
⁠// Add frontpage
⁠smStream.write({
⁠ url: "/",
⁠});
⁠// Add a static url to ex: about page
⁠smStream.write({
⁠ url: "/about",
⁠});
⁠// add all dynamic url to the sitemap which is fetched from a source.
⁠posts.forEach((element) => {
⁠ smStream.write({
⁠ url: `/${element.slug.current}`,
⁠ lastmod: element.publishedAt,
⁠ });
⁠});
⁠// tell sitemap that there is nothing more to add to the sitemap
smStream.end();
⁠// 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
⁠ res.write(sitemap);
⁠ // end and send the data to the user or service.
⁠ res.end();
⁠};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment