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

//pages/sitemap.xml.tsx
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-->
     <url>
       <loc>${SITE_URL}</loc>
     </url>
     <url>
       <loc>${SITE_URL}/contact}</loc>
     </url>
     ${postPaths
       .map((postPath) => {
         return `
       <url>
           <loc>${`${SITE_URL}/post/${postPath}`}</loc>
       </url>
     `
       })
       .join('')}
   </urlset>
 `
}

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
  res.write(sitemap)
  res.end()

  return {
    props: {},
  }
}

export default SiteMap

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

Hope this was helpful. Thanks!!

- Ayush 🙂