Published on

How to Generate a Dynamic Multi-Tenant Sitemap in Next.js


A sitemap is an essential part of a public website/blog that helps search engines to properly index our website. And that helps us to rank better and get more visitors.

So we must make sure we generate our sitemap properly to get the SEO benefits as well.

next-sitemap package is a popular way to generate a sitemap in Next.js. Let's see how to create it for a multi-tenant site.


npm install next-sitemap
// api/sitemap.jsx 
import { getServerSideSitemap } from "next-sitemap";
import Site from "example/SiteModel";

const getAllPages = async ({ host }) => {
  // Replace this with your logic to get the site's pages
  const site = await Site.getSiteByHost({ host });
  return site.pages;

export async function getServerSideProps(context) {
  // Generate sitemap.xml
  let host =;

  const ROOT_URL = `https://${host}`;
  const pages = await getAllPages({ host });
  const paths = pages
    .filter((page) => page.slug !== "/")
    .map((page) => {
      return {
        loc: ROOT_URL + page.slug,
        lastmod: new Date().toISOString(),

  const fields = [
      loc: ROOT_URL,
      lastmod: new Date().toISOString(),

  return getServerSideSitemap(context, fields);

// ref: notion blog repo
// @ts-ignore: Default export to prevent next.js errors
const SitemapPage = () => {
  // Weird NextJS thing
export default SitemapPage;

Happy generating sitemaps!