0
0
NextJSframework~5 mins

Sitemap.xml generation in NextJS

Choose your learning style9 modes available
Introduction

A sitemap.xml helps search engines find and understand your website pages easily. It improves your site's visibility on search results.

You want search engines like Google to index all your website pages quickly.
Your website has many pages or dynamic routes that change often.
You want to improve SEO by guiding search engines to important pages.
You have a blog or e-commerce site with frequently added content.
You want to provide metadata like last update time or page priority to search engines.
Syntax
NextJS
export async function GET() {
  const baseUrl = 'https://example.com';
  const routes = ['/', '/about', '/contact'];

  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${routes.map(route => `  <url>\n    <loc>${baseUrl}${route}</loc>\n  </url>`).join('\n')}\n</urlset>`;

  return new Response(sitemap, {
    headers: {
      'Content-Type': 'application/xml'
    }
  });
}

This code exports a GET function for a Next.js route that returns XML content.

The sitemap XML must follow the standard sitemap protocol for search engines.

Examples
This example creates a sitemap string for three pages: home, blog, and products.
NextJS
const routes = ['/', '/blog', '/products'];

const sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${routes.map(route => `  <url>\n    <loc>https://example.com${route}</loc>\n  </url>`).join('\n')}\n</urlset>`;
This sends the sitemap XML with the correct content type so browsers and crawlers understand it.
NextJS
return new Response(sitemap, {
  headers: { 'Content-Type': 'application/xml' }
});
Sample Program

This Next.js route handler generates a sitemap.xml dynamically listing four pages. When you visit this route, it returns the sitemap XML with correct headers.

NextJS
export async function GET() {
  const baseUrl = 'https://mywebsite.com';
  const routes = ['/', '/about', '/blog', '/contact'];

  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${routes.map(route => `  <url>\n    <loc>${baseUrl}${route}</loc>\n  </url>`).join('\n')}\n</urlset>`;

  return new Response(sitemap, {
    headers: {
      'Content-Type': 'application/xml'
    }
  });
}
OutputSuccess
Important Notes

Make sure the sitemap URL is accessible publicly so search engines can find it.

Update the routes list whenever you add or remove pages to keep the sitemap accurate.

You can automate sitemap generation for dynamic routes by fetching data inside the GET function.

Summary

Sitemap.xml helps search engines find your pages faster.

In Next.js, create a GET route that returns XML with page URLs.

Set the response header to 'application/xml' for correct recognition.