Contentstack LogoContentstack Logo

Creating a Sitemap for NextJS Websites

Note: This page is no longer maintained, and the underlying code may be outdated or unsupported. It may be removed in a future release. To learn how to create websites, refer to the Kickstarts and Starters documentation.

Sitemaps are machine-readable files that contain information about web pages. By using sitemaps, search engines can quickly identify and track the content of your website.

This guide explains how to set up sitemaps for your SSR and SSG NextJS websites.

Prerequisites

Steps to create a sitemap

  1. Ensure that the NextJS starter app is running on your machine.
  2. Create an XML file named sitemap.xml.tsx in the contentstack-nextjs-starter-app > pages folder using the following base code:
  3. export default function handler(req, res) {
      res.statusCode = 200
      res.setHeader('Content-Type', 'text/xml')
        // Instructing the CDN to cache the file
        res.setHeader('Cache-control', 'stale-while-revalidate, s-maxage=3600')
        // generate sitemap here
        const xml = `<?xml version="1.0" encoding="UTF-8"?>
        <urlset xmlns="<a href="http://www.sitemaps.org/schemas/sitemap/0.9">http://www.sitemaps.org/schema...</a>"> 
        <url>
          <loc><a href="http://www.myexample.com/foo.html<">http://www.myexample.com/foo.h...</a>;/loc>
          <lastmod>2022-01-01</lastmod>
        </url>
        </urlset>`
      res.end(xml)
    }
  4. Save the XML file.
  5. Note: You can customize the code as per your needs. Check out this sample code for reference.

  6. To view the sitemap of the NextJS website, add /sitemap.xml as a suffix to the NextJS website URL.
    Sitemap_in_NextJS.jpg
Was this article helpful?
^