Skip to content

How do I generate a “sitemap.xml” for my Next.js app on Vercel?

In this article, we will show you how to generate a sitemap for your Next.js deployment at both build time and runtime.

Generating the Sitemap at Build Time

Using the build step to generate the sitemap works best for deployments where content is also generated statically. If your most SEO-critical paths are known at build-time, such as landing pages, funnel-related content, and marketing material, then it is also advised that you generate the sitemap at build-time.

You can view the official Next.js example, with-sitemap, to learn how to generate a sitemap at build-time.

Generating the Sitemap at Runtime

Using the runtime to generate the sitemap works best for deployments where SEO-critical pages are highly dynamic or if you need a sitemap that can change over time. Do notice some restrictions may apply since you are unable to access the source code of the Next.js deployment at runtime.

To start, you can create a new file on pages/api/sitemap.js:

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="http://www.sitemaps.org/schemas/sitemap/0.9"> 
    <url>
      <loc>http://www.example.com/foo.html</loc>
      <lastmod>2021-01-01</lastmod>
    </url>
    </urlset>`

  res.end(xml)
}

Creating an API that will respond with an XML file.

The last step is to use a rewrite rule. This configuration will rewrite requests from /sitemap.xml to /api/sitemap:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/sitemap.xml',
        destination: '/api/sitemap',
      },
    ]
  },
}

A rule that allows api/sitemap to be remapped to /sitemap.xml.

Additional Resources

Another article that can be useful is "Create a Dynamic Sitemap with Next.js", by Lee Robinson.

Couldn't find the guide you need?