Server side index-sitemaps
Using getServerSideSitemapIndex API to generate sitemap.
Sample script to generate index-sitemap on server side with /app directory.
Create app/server-sitemap-index.xml/route.ts
file.
// app/server-sitemap-index.xml/route.ts
import { getServerSideSitemapIndex } from 'next-sitemap'
export async function GET(request: Request) {
// Method to source urls from cms
// const urls = await fetch('https//example.com/api')
return getServerSideSitemapIndex([
'https://example.com/path-1.xml',
'https://example.com/path-2.xml',
])
}
Sample script to generate index-sitemap on server side with /pages directory (legacy).
Create pages/server-sitemap-index.xml/index.tsx
file.
// pages/server-sitemap-index.xml/index.tsx
import { getServerSideSitemapIndexLegacy } from 'next-sitemap'
import { GetServerSideProps } from 'next'
export const getServerSideProps: GetServerSideProps = async (ctx) => {
// Method to source urls from cms
// const urls = await fetch('https//example.com/api')
return getServerSideSitemapIndexLegacy(ctx, [
'https://example.com/path-1.xml',
'https://example.com/path-2.xml',
])
}
// Default export to prevent next.js errors
export default function SitemapIndex() {}
Exclude server index sitemap from robots.txt
Now, next.js
is serving the dynamic index-sitemap from http://localhost:3000/server-sitemap-index.xml
.
List the dynamic sitemap page in robotsTxtOptions.additionalSitemaps
and exclude this path from static sitemap list.
// next-sitemap.config.js
/** @type {import('next-sitemap').IConfig} */
module.exports = {
siteUrl: 'https://example.com',
generateRobotsTxt: true,
exclude: ['/server-sitemap-index.xml'], // <= exclude here
robotsTxtOptions: {
additionalSitemaps: [
'https://example.com/server-sitemap-index.xml', // <==== Add here
],
},
}
In this way, next-sitemap
will manage the sitemaps for all your static pages and your dynamic index-sitemap
will be listed on robots.txt.