cs-icon.svg

Creating a Sitemap for NextJS Websites

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 Vercel edge 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?
^