Skip to content

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
sitemap.xml.tsx
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 Sitemap

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.

next.config.mjs
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.