Next (App Dir)
Luckily for us, the Next.js App Directory allows for Response objects to return in the Route Handlers.
We need to configure 2 route handlers, one for the sitemap index and another for the individual sitemap pages.
Directoryapp
Directorysitemap.xml
- route.ts
Directoryapi/v1/sitemap/[key]/[[…page]]
- route.ts
import { cartographer } from "@/modules/domain/sitemap"
export function GET() { return cartographer.$survey()}import type { Types } from "@/modules/cartographer/types"import { cartographer } from "@/modules/domain/sitemap"
export function GET(_: unknown, data: Types.Segment) { return cartographer.$draw(_, data)}Once you have this configured you will want to add a rewrite to your next.config file to make the dynamic routes for the individual sitemap pages a lot more readable.
const nextConfig = { rewrites: () => [ { source: "/sitemap/:path*", destination: "/api/v1/sitemap/:path*", } ],}Once this is configured you’ll have a sitemap index page at /sitemap.xml and individual sitemaps at /sitemap/<key>/<page>.xml. The <key> will match the name you pass into your static and dynamic declarations, and the <page> will be the specific page you’re looking at. Once you go over the urlsPerPage limit you’ll start seeming multiple pages being generated per key.