May 5, 2025
Web Development
Development, NextJS, Sitemap, Web Dev

Search engines like Google rely on sitemaps to discover and index your website’s content efficiently. With Next.js App Router, creating a dynamic sitemap.xml is straightforward. In this guide, you’ll learn how to create a sitemap endpoint that includes both static and dynamic routes using the App Router.
Create the file:
/app/api/sitemap/route.js
You’ll use the sitemap package to generate XML.
npm install sitemap
Also import the Readable stream:
import { Readable } from "stream";
Here’s an example that generates XML for both static and dynamic pages:
// app/api/sitemap/route.js
import { NextResponse } from "next/server";
import { SitemapStream, streamToPromise } from "sitemap";
import { Readable } from "stream";
// Example dynamic content fetchers
async function fetchPortfolios() {
const res = await fetch("https://your-api.com/portfolios");
if (!res.ok) return [];
const data = await res.json();
return data.map((item) => `/portfolio/${item.slug}`);
}
async function fetchArticles() {
const res = await fetch("https://your-api.com/articles");
if (!res.ok) return [];
const data = await res.json();
return data.map((item) => `/articles/${item.slug}`);
}
export async function GET() {
const staticPages = [
"/",
"/about",
"/portfolio",
"/articles",
"/contact",
];
const [portfolios, articles] = await Promise.all([
fetchPortfolios(),
fetchArticles(),
]);
const allPages = [...staticPages, ...portfolios, ...articles];
const sitemapStream = new SitemapStream({
hostname: "https://your-domain.com",
});
const xml = await streamToPromise(Readable.from(allPages).pipe(sitemapStream));
return new NextResponse(xml.toString(), {
status: 200,
headers: {
"Content-Type": "application/xml",
},
});
}
Once deployed, your sitemap is available at:
https://your-domain.com/api/sitemap
To ensure new content is reflected in the sitemap:
https://your-domain.com/api/sitemap
Generating a sitemap in Next.js using the App Router is efficient and SEO-friendly. You can include any number of static or dynamic pages with full control over the output format. Plus, you’re free to scale and automate sitemap updates as your site grows.
Technology, Web Development
May 5, 2025
Read More