How to Build a Dynamic Sitemap with Next.js
How to dynamically generate an XML sitemap in Next.js without extra libraries and improve SEO and search engine discoverability.
In this article, I walk through how to dynamically generate an XML sitemap for a Next.js application without installing external libraries—improving SEO and search engine discoverability.
We build the sitemap on top of a simple demo project with 3 routes (Home, Animes, and Anime).
What are SEO and Sitemaps?
SEO stands for Search Engine Optimization: the set of technical, content, and authority practices used to rank pages better on Google and other search engines, driving organic traffic.
A Sitemap is an XML file that explains your site structure, updates, and main pages to search engine crawlers so they can index everything properly.
Setting Up & Building pages/sitemap.xml.tsx
Inside pages/sitemap.xml.tsx, we use Next.js getServerSideProps to:
1. Define the baseUrl and fetch dynamic entries from the anime API.
2. Read the pages folder with Node's fs.readdirSync, filtering out internal files (_app.tsx, _document.tsx, _error.tsx, and sitemap.xml.tsx).
3. Escape XML-sensitive characters (&, <, >, spaces) on dynamic routes.
4. Combine static and dynamic URLs into an XML <urlset>, set Content-Type: text/xml, and write the response directly from the server.
import axios from "axios";
import fs from "fs";
import { GetServerSideProps } from "next";
export const getServerSideProps: GetServerSideProps = async ({ res }) => {
const baseUrl = "https://sitemap-anime.vercel.app";
const animes: string[] = await axios
.get("https://animechan.vercel.app/api/available/anime")
.then((res) => res.data);
const staticPages = fs
.readdirSync("pages")
.filter((staticPage) => {
return ![
"api",
"_app.tsx",
"_document.tsx",
"_error.tsx",
"sitemap.xml.tsx",
].includes(staticPage);
})
.map((staticPagePath) => `${baseUrl}/${staticPagePath}`);
const fields: string[] = animes.map((anime) => {
let animeFormatted = anime
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll(" ", "%20");
return `${baseUrl}/animes/${animeFormatted}`;
});
const sitemapsUrls = [...staticPages, ...fields];
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${sitemapsUrls
.map((url) => {
const path = url.replace("index.tsx", "");
return `
<url>
<loc>${path}</loc>
<lastmod>${new Date().toISOString()}</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
`;
})
.join("")}
</urlset>
`;
res.setHeader("Content-Type", "text/xml");
res.write(sitemap);
res.end();
return { props: {} };
};
export default function Site() {}Final Thoughts
This is not the only way to build a dynamic sitemap, but it keeps zero extra dependencies and runs automatically on the server whenever the route is requested. Full source on the without-library branch at github.com/rniguel/sitemap-anime.
Miguel Riquelme
Front-end Engineer. Software Engineering MBA student at USP/Esalq.