HomeCategoriesAll Tags

Adding sitemap to a Next.js application

Quick and easy tutorial on adding sitemap to your Next.js application...

If you are having pages directory structure in your next.js app then adding a sitemap is as easy as adding a sitemap.xml.jsx or .tsx component inside the pages directory and it will be build and published live along with your code.

Next thing to consider is that whether it is just few fixed pages or a lot of dynamic pages.

If just few fixed pages then write a sitemap.xml file manually and put it in public directory so that it will be published.

If there are many pages getting built dynamically then follow this steps.

  1. Create a sitemap.xml.jsx or .tsx file in pages directory.
  2. Use simple javascript logic to fetch the URLs of all the pages of your site and put them in xml format.
  3. This logic should go in getServerSideProps function so that it will run on build time.

Here's the complete example

const SITE_URL = 'https://heyayush.com'

const generateSiteMap = (postPaths: string[]) => {
  return `<?xml version="1.0" encoding="UTF-8"?>
   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
     <!--We manually set the URLs we know already-->
       .map((postPath) => {
         return `

function SiteMap() {
  // getServerSideProps will do the heavy lifting

export async function getServerSideProps({ res }: any) {
  // Gather the URLs for our site
  const posts = getAllPosts() // Logic of fetching dynamic URLs. Let's say I have 100 posts then it fetches them
  const postPaths = posts.map((p) => p.slug) // just mapping the slugs of the post because all we need is URLs for generating sitemaps.

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

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

  return {
    props: {},

export default SiteMap

That's all. With these simple steps we can generate a sitemap.

Hope this was helpful. Thanks!!

- Ayush 🙂