Back to Snippets
Next.jsTypeScript

Next.js Sitemap Generator

Automatically generate a sitemap.xml from static and dynamic routes.

nextjssitemapseoxml
import type { MetadataRoute } from class=class="text-emerald-400">"text-emerald-400">'next'

const BASE_URL = class=class="text-emerald-400">"text-emerald-400">'https:class=class="text-emerald-400">"text-gray">//example.com'

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const staticPages = [class=class="text-emerald-400">"text-emerald-400">'', class=class="text-emerald-400">"text-emerald-400">'/about', class=class="text-emerald-400">"text-emerald-400">'/contact', class=class="text-emerald-400">"text-emerald-400">'/blog']

  const staticEntries = staticPages.map(page => ({
    url: class="text-emerald-400">`${BASE_URL}${page}`,
    lastModified: new Date(),
    changeFrequency: class=class="text-emerald-400">"text-emerald-400">'monthly' as const,
    priority: page === class=class="text-emerald-400">"text-emerald-400">'' ? 1.0 : 0.8,
  }))

  class=class="text-emerald-400">"text-gray">// Fetch dynamic routes
  const res = await fetch(class="text-emerald-400">`${BASE_URL}/api/posts`, {
    next: { revalidate: 3600 },
  })
  const posts = res.ok ? await res.json() : []

  const postEntries = posts.map((post: { slug: string; updatedAt: string }) => ({
    url: class="text-emerald-400">`${BASE_URL}/blog/${post.slug}`,
    lastModified: new Date(post.updatedAt),
    changeFrequency: class=class="text-emerald-400">"text-emerald-400">'weekly' as const,
    priority: 0.6,
  }))

  return [...staticEntries, ...postEntries]
}

How to Use

Save as app/sitemap.ts. Next.js automatically serves it at /sitemap.xml. Add all static pages and dynamically fetch slugs from your API or database. Google will discover and index your pages.

Related Technology

Next.js

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call