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`.
In this `getServerSideProps` we are first fetching all the posts (this is using Sanity.io) and then running them through a `generateSiteMap` function.
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:
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.

