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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Next.js turns a default-exported sitemap function into an XML sitemap automatically from the array you return.
- 2Deriving routes from live database records keeps your sitemap in sync without manual edits.
- 3Reading the base URL from an environment variable lets the same code produce correct URLs across environments.
Related explainers
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
7 steps
javascript
import { useState, useCallback, useRef } from 'react'; function LikeButton({ postId, initialLiked, initialCount }) { const [liked, setLiked] = useState(initialLiked);
Optimistic like button with React
optimistic-ui
abortcontroller
error-handling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/generating-a-dynamic-sitemap-in-next-js-explained-javascript-c7c3/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.