Next (Pages Dir)
The Next.js page directory is a bit funny when it comes to Reponse objects and you can only write API routes in the api directory. So the sitemap index is a bit funky, using getServerSideProps is a weird way.
We will also need to configure the individual page API route, which luckily for us, we can do as a API route.
Directorypages
- sitemap.xml.tsx
Directoryapi/v1/sitemap/[key]
- [[…page]].ts
import { cartographer } from '@/library/sitemap'import type { GetServerSideProps } from 'next'
const Sitemap = () => null
export const getServerSideProps: GetServerSideProps = async (context) => { const { res: response } = context
const response0 = await cartographer.$survey() const content = await response0.text()
response.setHeader('Content-Type', 'text/xml') response.write(content) response.end()
return { props: {}, }}
export default Sitemapimport { cartographer } from '@/library/sitemap'import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler( request: NextApiRequest, response: NextApiResponse,) { if (request.method !== 'GET') { response.status(403) return }
const { key, page } = request.query if (typeof key !== 'string' || typeof page === 'string') { response.status(400) return }
const response0 = await cartographer.$draw(null, { params: Promise.resolve({ key, page, }), })
const text = await response0.text() response.setHeader('Content-Type', 'application/xml') response.status(200) response.send(text)}You’ll notice we’ve wrapped our params in a Promise.resolve, this is because the param structure mimics the Next.js App directory type definitions.
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 = { async rewrites() { return [ { 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.