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:

1
export default function handler(req, res) {
2
3
res.statusCode = 200
4
res.setHeader('Content-Type', 'text/xml')
5
6
// Instructing the Vercel edge to cache the file
7
res.setHeader('Cache-control', 'stale-while-revalidate, s-maxage=3600')
8
9
// generate sitemap here
10
const xml = `<?xml version="1.0" encoding="UTF-8"?>
11
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
12
<url>
13
<loc>http://www.example.com/foo.html</loc>
14
<lastmod>2021-01-01</lastmod>
15
</url>
16
</urlset>`
17
18
res.end(xml)
19
}
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:

1
module.exports = {
2
async rewrites() {
3
return [
4
{
5
source: '/sitemap.xml',
6
destination: '/api/sitemap',
7
},
8
]
9
},
10
}
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?