what-works-global

sitemap

by what-works-global
payload-packages
SEO & metadata
v3
>=3.30.0 <4

Overview

Summary generated from the README

Generates a sitemap index and per-collection XML sitemaps split into chunks, regenerated lazily from the database after collection hooks mark the cache dirty. Next.js route helpers and a robots.txt generator are included, and the delivery, caching and invalidation layers can be replaced for other stacks. Requires Payload 3.30 or later.

Features

  • Sitemap index with per-collection files chunked at a configurable size
  • Hook-driven invalidation via Next.js cache tags, with memory or custom cache adapters
  • Drafts excluded automatically for collections with drafts enabled
  • Admin checkbox to exclude individual documents from the sitemap
  • robots.txt helpers that block indexing outside production
  • Optional REST endpoints and JSON entries for decoupled frontends

Use cases

  • Add search-engine sitemaps to a Payload and Next.js site hosted on Vercel
  • Serve a sitemap from a headless Payload CMS for an Astro or SvelteKit frontend
  • Resolve the site URL per host for multi-domain deployments

From the author

Payload plugin that generates chunked, lazily cached XML sitemaps with hook-driven invalidation and robots.txt helpers. Next.js + Vercel work out of the box; every layer is overridable for other stacks.

Installation

npm i @whatworks/payload-sitemap

16

Stars

1

Forks

2

Open Issues

3 days ago

Last Updated

195

Weekly Downloads

v0.2.1

npm Version

130.8 KB

Unpacked Size

0

Dependencies

Repository stars

16+1 since Sep 6

Show data
Repository stars by day (UTC)
DateStars
Dec 5, 202616
Dec 4, 202616
Dec 3, 202616
Dec 2, 202616
Dec 1, 202616
Nov 30, 202616
Nov 29, 202616
Nov 28, 202616
Nov 27, 202616
Nov 26, 202616
Nov 25, 202616
Nov 24, 202616
Nov 23, 202616
Nov 22, 202616
Nov 21, 202616
Nov 20, 202616
Nov 19, 202616
Nov 18, 202616
Nov 17, 202615
Nov 16, 202615
Nov 15, 202615
Nov 14, 202615
Nov 13, 202615
Nov 12, 202615
Nov 11, 202615
Nov 10, 202615
Nov 9, 202615
Nov 8, 202615
Nov 7, 202615
Nov 6, 202615
Nov 5, 202615
Nov 4, 202615
Nov 3, 202615
Nov 2, 202615
Nov 1, 202615
Oct 31, 202615
Oct 30, 202615
Oct 29, 202615
Oct 28, 202615
Oct 27, 202615
Oct 26, 202615
Oct 25, 202615
Oct 24, 202615
Oct 23, 202615
Oct 22, 202615
Oct 21, 202615
Oct 20, 202615
Oct 19, 202615
Oct 18, 202615
Oct 17, 202615
Oct 16, 202615
Oct 15, 202615
Oct 14, 202615
Oct 13, 202615
Oct 12, 202615
Oct 11, 202615
Oct 10, 202615
Oct 9, 202615
Oct 8, 202615
Oct 7, 202615
Oct 6, 202615
Oct 5, 202615
Oct 4, 202615
Oct 3, 202615
Oct 2, 202615
Oct 1, 202615
Sep 30, 202615
Sep 29, 202615
Sep 28, 202615
Sep 27, 202615
Sep 26, 202615
Sep 25, 202615
Sep 24, 202615
Sep 23, 202615
Sep 22, 202615
Sep 21, 202615
Sep 20, 202615
Sep 19, 202615
Sep 18, 202615
Sep 17, 202615
Sep 16, 202615
Sep 15, 202615
Sep 14, 202615
Sep 13, 202615
Sep 12, 202615
Sep 11, 202615
Sep 10, 202615
Sep 9, 202615
Sep 8, 202615
Sep 7, 202615
Sep 6, 202615

Shared by 12 plugins in what-works-global/payload-packages.

npm weekly downloads

243+225 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 2026243
Dec 4, 2026289
Dec 3, 2026257
Dec 2, 2026262
Dec 1, 2026291
Nov 30, 2026289
Nov 29, 2026245
Nov 28, 2026195
Nov 27, 2026148
Nov 26, 2026153
Nov 25, 2026168
Nov 24, 2026182
Nov 23, 2026183
Nov 22, 2026213
Nov 21, 2026217
Nov 20, 2026303
Nov 19, 2026265
Nov 18, 2026329
Nov 17, 2026288
Nov 16, 2026298
Nov 15, 2026305
Nov 14, 2026334
Nov 13, 2026284
Nov 12, 2026284
Nov 11, 2026233
Nov 10, 2026262
Nov 9, 2026254
Nov 8, 2026220
Nov 7, 2026186
Nov 6, 2026154
Nov 5, 2026133
Nov 4, 2026108
Nov 3, 202677
Nov 2, 202676
Nov 1, 202671
Oct 31, 202664
Oct 30, 202661
Oct 29, 202653
Oct 28, 202613
Oct 27, 202618
Oct 26, 202618
Oct 25, 202626
Oct 24, 202627
Oct 23, 202618
Oct 22, 202626
Oct 21, 202633
Oct 20, 202628
Oct 19, 202626
Oct 18, 202630
Oct 17, 202664
Oct 16, 202665
Oct 15, 202661
Oct 14, 202664
Oct 13, 202667
Oct 12, 202668
Oct 11, 202681
Oct 10, 202652
Oct 9, 202671
Oct 8, 202668
Oct 7, 202658
Oct 6, 202658
Oct 5, 202657
Oct 4, 202633
Oct 3, 202635
Oct 2, 202615
Oct 1, 202625
Sep 30, 202628
Sep 29, 202625
Sep 28, 202625
Sep 27, 202627
Sep 26, 202621
Sep 25, 202621
Sep 24, 202614
Sep 23, 202622
Sep 22, 202626
Sep 21, 202630
Sep 20, 202630
Sep 19, 202630
Sep 18, 202632
Sep 17, 202629
Sep 16, 202620
Sep 15, 202615
Sep 14, 202612
Sep 13, 202610
Sep 12, 20269
Sep 11, 20269
Sep 10, 202613
Sep 9, 202612
Sep 8, 202613
Sep 7, 202614
Sep 6, 202618

Each point is npm's rolling 7-day download count.

Health Score

62/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1064440892-sitemap.svg)](https://payloaddirectory.dev/plugins/1064440892-sitemap)
HTML
<a href="https://payloaddirectory.dev/plugins/1064440892-sitemap"><img src="https://payloaddirectory.dev/badge/1064440892-sitemap.svg" alt="Payload Directory"></a>
Updated Dec 2, 2026Created Sep 26, 2025Published Jul 10, 2026

README

@whatworks/payload-sitemap

@whatworks/payload-sitemap

 

Chunked, lazily cached XML sitemaps for Payload with hook-driven invalidation and robots.txt helpers.

Next.js + Vercel work with near-zero config; every layer — delivery, caching, invalidation, robots output — is overridable for other stacks (decoupled frontends, self-hosted servers, SSG builds).

How it works

  • Lazy generation. Nothing regenerates on save. Collection hooks only mark a group's cache dirty (deduped per request, run after the response so the transaction has committed). The next sitemap request regenerates that group from the database — slug changes, breadcrumb cascades (e.g. plugin-nested-docs re-saving children), publishes, unpublishes, and deletes all come out correct without any change detection.
  • One sitemap file per collection, chunked. /sitemap.xml is a <sitemapindex> referencing pages-1.xml, posts-1.xml, … split at chunkSize (default 25,000; protocol limit 50,000).
  • Lean queries. Docs are fetched in pages of 1,000 with select, depth: 0, and a _status filter applied only when the collection actually has drafts enabled.
  • Caching: with 'auto' (default), entries are cached in the Next.js Data Cache with tags (revalidateTag invalidation — works across serverless instances on Vercel) and fall back to an in-memory cache outside Next. Responses also carry Cache-Control: s-maxage so a CDN absorbs crawler traffic.

Quick start (Payload inside Next.js)

// payload.config.ts
import { sitemapPlugin } from '@whatworks/payload-sitemap'

export default buildConfig({
  plugins: [
    sitemapPlugin({
      collections: {
        pages: {
          path: ({ doc }) => (doc.slug === 'home' ? '/' : `/${doc.slug}`),
          select: { slug: true },
        },
      },
    }),
  ],
})
// app/sitemap.xml/route.ts
import config from '@payload-config'
import { createSitemapIndexRoute } from '@whatworks/payload-sitemap/next'

export const dynamic = 'force-dynamic'
export const { GET } = createSitemapIndexRoute({ config })
// app/sitemaps/[sitemap]/route.ts
import config from '@payload-config'
import { createSitemapChunkRoute } from '@whatworks/payload-sitemap/next'

export const dynamic = 'force-dynamic'
export const { GET } = createSitemapChunkRoute({ config })
// app/robots.ts
import config from '@payload-config'
import { createRobots } from '@whatworks/payload-sitemap/next'

export default createRobots({ config })

This is the entire setup — no env vars required. robots.txt disallows everything outside production (VERCEL_ENV/NODE_ENV), and disallows the admin + API routes in production.

How siteUrl is resolved

Every URL in the sitemap is joined onto the first available of:

  1. the siteUrl plugin option — a string, or a function ({ request }) => string with full control
  2. the incoming request — x-forwarded-proto/x-forwarded-host, then Host, then the request URL's origin
  3. SITE_URL → NEXT_PUBLIC_SERVER_URL
  4. https://$VERCEL_PROJECT_PRODUCTION_URL

The request deliberately outranks the env vars: with zero configuration, a deployment answering on several hosts (example.com, staging.example.com, *.vercel.app) emits each sitemap on the host it was requested from. Set the siteUrl option when multiple public hosts must emit one canonical domain. The env vars cover request-less contexts (build steps, background jobs); Vercel's project URL comes last because it is derived — and frozen at build time — rather than configured. The app/robots.ts helper reads next/headers when the origin isn't pinned by an option string, which makes that route dynamic.

Host headers are client-controlled, so request-derived origins are never written to the shared cache — entries are cached as site-relative paths and joined onto the resolved origin per request. A forged Host can only distort the forger's own response, provided your proxy/CDN sets x-forwarded-host itself (Vercel does) instead of passing a client-supplied value through to a shared HTTP cache.

Plugin options

sitemapPlugin({
  // Required. Per-collection config, typed against your generated types.
  collections: {
    pages: {
      // Return a path (joined to siteUrl) or an absolute URL (used verbatim).
      // Return null/undefined to omit the doc.
      path: ({ doc }) => `/${doc.slug}`,
      // Fields your path()/lastMod() need. id/updatedAt are always included.
      select: { slug: true, breadcrumbs: true },
      lastMod: 'publishedAt', // field name, (doc) => Date, or false. Default 'updatedAt'
      where: {}, // extra query constraints
      chunkSize: 10_000, // per-collection override
      changeFreq: 'weekly', // opt-in; Google ignores it
      priority: 0.5, // opt-in; Google ignores it
      // Override the default invalidation heuristic (invalidate on any change
      // except a draft save with no published transition):
      shouldInvalidate: ({ doc, previousDoc, operation }) => true,
    },
  },

  // String, or a function with full control (multi-tenant, per-request logic).
  // Default: incoming request → env chain (see “How siteUrl is resolved”).
  siteUrl: ({ request }) => `https://${request.headers.get('host')}`,
  trailingSlash: false,
  chunkSize: 25_000,

  // Extra routes: static array, or an async function (e.g. read a global).
  routes: async ({ payload }) => [{ path: '/search' }],

  // Injected admin fields. Default: an `excludeFromSitemap` sidebar checkbox.
  // `group` nests them inside the group field (or named tab) with that name —
  // e.g. an existing `metadata` group. Dot notation reaches nested containers
  // (`'seo.metadata'`); missing segments are created as groups on collections
  // that lack them. The exclude flag then lives at `metadata.excludeFromSitemap`.
  adminFields: { exclude: true, group: 'metadata' },

  // 'auto' (default) | 'memory' | 'none' | custom { wrap, invalidate } adapter.
  cache: 'auto',

  // REST endpoints under the API route. DISABLED by default — the Next route
  // handlers above are the primary delivery.
  endpoints: {
    path: '/sitemap', // → /api/sitemap/index.xml, /api/sitemap/pages-1.xml
    access: ({ req }) => true, // XML access; default public once enabled
    json: true, // /api/sitemap/entries.json; default access: req.user
    cacheControl: 'public, max-age=0, s-maxage=600, stale-while-revalidate=86400',
    origin: 'https://cms.example.com', // index chunk-URL origin; default: request origin
  },

  // Defaults for robots output (createRobots / generateRobotsTxt).
  robots: {
    allowIndexing: undefined, // default VERCEL_ENV/NODE_ENV
    disallow: ['/drafts/'], // appended to the default rule
    rules: undefined, // replace default rules entirely
    sitemaps: undefined, // default `${siteUrl}/sitemap.xml`
    transform: (robots) => robots, // final say over the computed output
  },

  disabled: false, // keeps injected fields for schema/migration consistency
})

Decoupled frontends & other stacks

Payload standalone as a headless CMS, frontend elsewhere (Astro, SvelteKit, …):

  1. Enable the REST endpoints (endpoints: true). The sitemap serves from https://cms.example.com/api/sitemap/index.xml.
  2. Either proxy /sitemap.xml → the CMS endpoint from your frontend, or declare it cross-host in the frontend's robots.txt (sanctioned by sitemaps.org): Sitemap: https://cms.example.com/api/sitemap/index.xml
  3. For build-time SSG, fetch /api/sitemap/entries.json (authenticated by default) or call getSitemapEntries(payload) in a build script and render however you like.
  4. generateRobotsTxt(config, overrides?) returns a robots.txt string for any server.

On a long-running self-hosted server, set cache: 'memory' — hooks invalidate it in-process. For anything else, implement the two-method SitemapCache interface (wrap, invalidate) — e.g. backed by Redis — and pass it as cache.

Public API

Export (.)Purpose
sitemapPlugin(config)The Payload plugin
getSitemapEntries(payload, opts?)All cached entries keyed by group
invalidateSitemap(payload, groups?)Manual invalidation (e.g. from a global's hook that feeds routes)
generateRobotsTxt(config, overrides?)robots.txt string for any delivery
getIndexItems / getChunkEntries / buildUrlsetXml / buildSitemapIndexXmlBuilding blocks for custom delivery
SITEMAP_CACHE_TAG / sitemapCacheTag(group)Next cache tags, for custom revalidateTag calls
Export (./next)Purpose
createSitemapIndexRoute({ config, chunksPath?, cacheControl? })GET handler for app/sitemap.xml/route.ts
createSitemapChunkRoute({ config, param?, cacheControl? })GET handler for app/sitemaps/[sitemap]/route.ts
createRobots({ config, ...robotsOverrides })Default export for app/robots.ts

Development

pnpm dev (from packages/sitemap) boots the sandbox in dev/ — a Next app with the admin at /admin (login form comes prefilled) and a demo page at / listing every delivery surface plus the live cached entries. It seeds a drafts-enabled pages collection, a draftless legal collection, a draft-only doc and an excludeFromSitemap doc into a throwaway SQLite database (dev/.dbs/, gitignored — delete it to reseed). Publish/delete docs in the admin and reload to watch hook-driven invalidation land.

Notes

  • changefreq/priority are opt-in because Google ignores both; lastmod is the only freshness signal it uses. Skipping them keeps the admin sidebar and XML lean.
  • Invalidation timing: hooks schedule invalidation via Next's after() (post-response, post-commit; uses waitUntil on Vercel) with a plain macrotask fallback outside Next. revalidateTag is called with { expire: 0 } for instant expiry on Next 16; Next 15 ignores the extra argument.
  • CDN staleness trade-off: the default s-maxage=600 means a CDN may serve a sitemap up to 10 minutes stale after a publish — regeneration is cheap behind it, so tune cacheControl if you need tighter freshness.
  • Drafts are never included: the _status filter applies exactly when the collection has drafts enabled, so collections without drafts also work (no _status query error).

Similar plugins