javascript 27 lines · 5 steps

Generating a dynamic sitemap in Next.js

A sitemap.js route that merges static pages with published articles pulled from the database.

Explained by highlit
1import { db } from '@/lib/db'
2 
3const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? 'https://example.com'
4 
5export default async function sitemap() {
6 const articles = await db.article.findMany({
7 where: { status: 'published', publishedAt: { not: null } },
8 select: { slug: true, updatedAt: true, publishedAt: true },
9 orderBy: { publishedAt: 'desc' },
10 })
11 
12 const staticRoutes = ['', '/blog', '/about'].map((path) => ({
13 url: `${SITE_URL}${path}`,
14 lastModified: new Date(),
15 changeFrequency: 'daily',
16 priority: path === '' ? 1 : 0.7,
17 }))
18 
19 const articleRoutes = articles.map((article) => ({
20 url: `${SITE_URL}/blog/${article.slug}`,
21 lastModified: article.updatedAt ?? article.publishedAt,
22 changeFrequency: 'weekly',
23 priority: 0.6,
24 }))
25 
26 return [...staticRoutes, ...articleRoutes]
27}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Next.js turns a default-exported sitemap function into an XML sitemap automatically from the array you return.
  2. 2Deriving routes from live database records keeps your sitemap in sync without manual edits.
  3. 3Reading the base URL from an environment variable lets the same code produce correct URLs across environments.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Generating a dynamic sitemap in Next.js — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code