Next.js Sitemap
Automatically generate sitemap in Next.js for static routes.
app/sitemap.ts
ts1/** 2 * @see https://github.com/iamvishnusankar/next-sitemap/issues/895#issuecomment-2741949689 3 */ 4 5import fs from "fs"; 6import path from "path"; 7 8import { siteConfig } from "@/config/site"; 9import type { MetadataRoute } from "next"; 10 11async function getStaticRoutes( 12 dir = "src/app", 13 parentPath = "" 14): Promise<string[]> { 15 const currentDir = path.join(process.cwd(), dir); 16 const entries = fs.readdirSync(currentDir, { withFileTypes: true }); 17 18 let routes: string[] = []; 19 20 for (const entry of entries) { 21 const fullPath = path.join(currentDir, entry.name); 22 23 if (entry.isDirectory()) { 24 const routePath = path.join(parentPath, entry.name); 25 26 const hasPage = ["page.tsx", "page.jsx"].some((file) => 27 fs.existsSync(path.join(fullPath, file)) 28 ); 29 30 if (hasPage) { 31 routes.push(`/${routePath}`); 32 } 33 34 const nestedRoutes = await getStaticRoutes( 35 path.join(dir, entry.name), 36 routePath 37 ); 38 39 const nestedStaticRoutes = nestedRoutes.filter( 40 (route) => !route.match(/\[.+\]/) 41 ); 42 43 routes = routes.concat(nestedStaticRoutes); 44 } 45 } 46 47 return parentPath === "" ? ["/", ...routes] : routes; 48} 49 50export default async function sitemap(): Promise<MetadataRoute.Sitemap> { 51 const allRoutes = (await Promise.all([getStaticRoutes()])).flat(); 52 53 return allRoutes.map((route) => ({ 54 url: encodeURI(`${siteConfig.url}${route}`), 55 lastModified: new Date().toISOString(), 56 priority: route === "/" ? 1 : 0.8, 57 })); 58}