How to Generate a Dynamic Sitemap with Nextjs

Written on 2023-03-22 by Adam Drake - 3 min read

Image of How to Generate a Dynamic Sitemap with Nextjs

A website sitemap is a hierarchical map of the content of a website. It helps search engine crawlers to understand the structure of a website and consequently make it easier for them to index the content of the website. A sitemap also helps users to easily navigate to the content they are looking for by providing a clear overview of the structure of a website.

What is needed for a Sitemap in NextJs

Essentially what is needed for a sitemap in Nextjs is a `sitemap.xml` file. A Sitemap.xml file is an XML file that lists URLs and other information about a website for search engines. An example of that can be seen on my site. This file can then be inputted into the Google Search Console so Google knows where to find your sitemap so it can use it to index all relevant links on your site.

How to Generate a Sitemap in Nextjs

One way to create a sitemap is to add links on your site to the sitemap.xml file manually. This is fine (I guess) for pages which you know will definitely be on your site for a long time.

However, if you are working on a blog site or a site with articles where the content is generated elsewhere (headless CMS) then manually adding every post will be very time consuming, prone to errors and likely that something will be missed.

Therefore it's better to implement a solution that can find the desired links whenever the site is visited. To do this we use the power of Nextjs and specifically `getServerSideProps`.

export const getServerSideProps: GetServerSideProps = async ({ res }) => {
  // We make an API call to gather the URLs for our site
  const posts = await client.fetch(`*[_type == "post"]`);

  // We generate the XML sitemap with the posts data
  const sitemap = generateSiteMap(posts);

  res.setHeader('Content-Type', 'text/xml');
  // we send the XML to the browser
  res.write(sitemap);
  res.end();

  return {
    props: {},
  };
};

In this `getServerSideProps` we are first fetching all the posts (this is using Sanity.io) and then running them through a `generateSiteMap` function.

function generateSiteMap(posts: Post[]) {
  return `<?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
      <!--We manually set the two URLs we know already-->
      <url>
        <loc>${MAIN_DOMAIN}</loc>
      </url>
      <url>
        <loc>${MAIN_DOMAIN}/about</loc>
      </url>
      <url>
        <loc>${MAIN_DOMAIN}/books</loc>
      </url>
      <url>
        <loc>${MAIN_DOMAIN}/blog</loc>
      </url>
      ${posts
        .map(({ slug }) => {
          return `
        <url>
            <loc>${`${MAIN_DOMAIN}/blog/${slug}`}</loc>
        </url>
      `;
        })
        .join('')}
    </urlset>
  `;
}

This `generateSiteMap` function is returning a template literal of the xml that will then be sent back in the `response`. As you can see some of the links are manually declared like `<loc>${MAIN_DOMAIN}/about</loc>`. However, the nice part comes when the function iterates over the `posts` array and spits out any post slug as a link:

${posts
        .map(({ slug }) => {
          return `
        <url>
            <loc>${`${MAIN_DOMAIN}/blog/${slug}`}</loc>
        </url>
      `;
        })
        .join('')}

As this `posts` array is called fresh each time from the headless CMS this allows the generated site map to always be up to date with the latest blog links! Amazing!

Conclusion

Once you have made a site you probably want people visiting it. Whether you like it or not, your site being found by search engines is a necessity so having a sitemap really helps these search engines become aware of what your site is about and helps them make decisions about who should see links to your site.

Being able to generate these as dynamically as possible means less manual effort and greater accuracy. Hope this blog post helps!

More can be found on the Nextjs Documentation.

Loading...

Adam Drake AI Selfie

Written by Adam Drake

Adam Drake is a Frontend React Developer who is very passionate about the quality of the web. He lives with his wife and three children in Prague in the Czech Republic.

Adam Drakes Site © 2024