Builds index and child sitemaps from collections, static pages and custom URL lists, run as a Payload job and stored through Payload storage adapters. Only published, publicly readable documents are listed. It supports images, hreflang, per-locale domains and per-tenant sitemaps, plus an admin page and dashboard widget. Version 1.x targets Payload 4 and needs a jobs runner.
Sitemaps for Payload, generated by a job and stored through any Payload storage adapter.
Installation
npm i @seshuk/payload-plugin-sitemap6
Stars
0
Forks
5
Open Issues
3 days ago
Last Updated
7
Weekly Downloads
v0.1.0
npm Version
659.6 KB
Unpacked Size
0
Dependencies
6+6 since Oct 11
| Date | Stars |
|---|---|
| Dec 5, 2026 | 6 |
| Dec 4, 2026 | 6 |
| Dec 3, 2026 | 6 |
| Dec 2, 2026 | 6 |
| Dec 1, 2026 | 6 |
| Nov 30, 2026 | 6 |
| Nov 29, 2026 | 6 |
| Nov 28, 2026 | 6 |
| Nov 27, 2026 | 6 |
| Nov 26, 2026 | 6 |
| Nov 25, 2026 | 6 |
| Nov 24, 2026 | 6 |
| Nov 23, 2026 | 6 |
| Nov 22, 2026 | 6 |
| Nov 21, 2026 | 6 |
| Nov 20, 2026 | 6 |
| Nov 19, 2026 | 6 |
| Nov 18, 2026 | 6 |
| Nov 17, 2026 | 6 |
| Nov 16, 2026 | 6 |
| Nov 15, 2026 | 6 |
| Nov 14, 2026 | 6 |
| Nov 13, 2026 | 6 |
| Nov 12, 2026 | 6 |
| Nov 11, 2026 | 6 |
| Nov 10, 2026 | 6 |
| Nov 9, 2026 | 6 |
| Nov 8, 2026 | 6 |
| Nov 7, 2026 | 6 |
| Nov 6, 2026 | 6 |
| Nov 5, 2026 | 6 |
| Nov 4, 2026 | 6 |
| Nov 3, 2026 | 5 |
| Nov 2, 2026 | 5 |
| Nov 1, 2026 | 5 |
| Oct 31, 2026 | 5 |
| Oct 30, 2026 | 5 |
| Oct 29, 2026 | 5 |
| Oct 28, 2026 | 5 |
| Oct 27, 2026 | 5 |
| Oct 26, 2026 | 5 |
| Oct 25, 2026 | 5 |
| Oct 24, 2026 | 5 |
| Oct 23, 2026 | 5 |
| Oct 22, 2026 | 5 |
| Oct 21, 2026 | 5 |
| Oct 20, 2026 | 5 |
| Oct 19, 2026 | 4 |
| Oct 18, 2026 | 4 |
| Oct 17, 2026 | 3 |
| Oct 16, 2026 | 3 |
| Oct 15, 2026 | 3 |
| Oct 14, 2026 | 0 |
| Oct 13, 2026 | 0 |
| Oct 12, 2026 | 0 |
| Oct 11, 2026 | 0 |
7−30 since Oct 18
| Date | Weekly downloads |
|---|---|
| Dec 5, 2026 | 7 |
| Dec 4, 2026 | 8 |
| Dec 3, 2026 | 11 |
| Dec 2, 2026 | 12 |
| Dec 1, 2026 | 13 |
| Nov 30, 2026 | 16 |
| Nov 29, 2026 | 15 |
| Nov 28, 2026 | 14 |
| Nov 27, 2026 | 13 |
| Nov 26, 2026 | 11 |
| Nov 25, 2026 | 7 |
| Nov 24, 2026 | 6 |
| Nov 23, 2026 | 3 |
| Nov 22, 2026 | 8 |
| Nov 21, 2026 | 14 |
| Nov 20, 2026 | 20 |
| Nov 19, 2026 | 22 |
| Nov 18, 2026 | 30 |
| Nov 17, 2026 | 35 |
| Nov 16, 2026 | 40 |
| Nov 15, 2026 | 37 |
| Nov 14, 2026 | 41 |
| Nov 13, 2026 | 39 |
| Nov 12, 2026 | 38 |
| Nov 11, 2026 | 37 |
| Nov 10, 2026 | 43 |
| Nov 9, 2026 | 42 |
| Nov 8, 2026 | 43 |
| Nov 7, 2026 | 34 |
| Nov 6, 2026 | 32 |
| Nov 5, 2026 | 36 |
| Nov 4, 2026 | 32 |
| Nov 3, 2026 | 35 |
| Nov 2, 2026 | 36 |
| Nov 1, 2026 | 35 |
| Oct 31, 2026 | 38 |
| Oct 30, 2026 | 45 |
| Oct 29, 2026 | 39 |
| Oct 28, 2026 | 34 |
| Oct 27, 2026 | 25 |
| Oct 26, 2026 | 29 |
| Oct 25, 2026 | 39 |
| Oct 24, 2026 | 72 |
| Oct 23, 2026 | 63 |
| Oct 22, 2026 | 63 |
| Oct 21, 2026 | 63 |
| Oct 20, 2026 | 58 |
| Oct 19, 2026 | 49 |
| Oct 18, 2026 | 37 |
Each point is npm's rolling 7-day download count.
Health Score
Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.
Badge for your README
[](https://payloaddirectory.dev/plugins/1418690377-root)<a href="https://payloaddirectory.dev/plugins/1418690377-root"><img src="https://payloaddirectory.dev/badge/1418690377-root.svg" alt="Payload Directory"></a>README
Build sitemap.xml from your Payload content, store them in any storage, and keep them fresh.
sources array. url: '/blog/:slug' is enough.upload. Optional publish to a CDN.The Sitemap page, with the last run and the file table:

The dashboard widget:

| Plugin | Payload | Node.js | Install |
|---|---|---|---|
| 1.x | 4 | 24.22.1+ | @seshuk/payload-plugin-sitemap@beta |
| 0.x | 3 | 22+ | @seshuk/payload-plugin-sitemap@0 |
beta npm tag while Payload 4 is in beta.@payloadcms/next) and TanStack Start (@payloadcms/tanstack-start).# Payload 4
pnpm add @seshuk/payload-plugin-sitemap@beta
# Payload 3
pnpm add @seshuk/payload-plugin-sitemap@0
The smallest setup lists one collection with a URL pattern:
import { sitemap } from '@seshuk/payload-plugin-sitemap'
import { buildConfig } from 'payload'
export default buildConfig({
// ...
jobs: {
autoRun: [{ cron: '* * * * *', queue: 'default' }],
},
plugins: [
sitemap({
siteUrl: 'https://example.com',
sources: [{ type: 'collection', collection: 'posts', url: '/blog/:slug' }],
}),
],
})
A fuller example:
sitemap({
siteUrl: 'https://example.com',
sources: [
{ type: 'static', entries: [{ url: '/', priority: 1 }, { url: '/contact' }] },
{
type: 'collection',
collection: 'pages',
url: ({ doc }) => (doc.slug === 'home' ? '/' : `/${doc.slug}`),
changefreq: 'weekly',
priority: ({ doc }) => (doc.slug === 'home' ? 1 : 0.8),
fields: true,
},
{
type: 'collection',
collection: 'posts',
url: '/blog/:category.slug/:slug',
images: ['cover', 'gallery.image'],
query: { where: { hidden: { not_equals: true } }, sort: '-publishedAt' },
},
],
jobs: { regenerate: { delay: 10_000 } },
})
payload generate:importmap, so the admin panel can find the Sitemap page and widget.jobs.autoRun as above, payload jobs:run on a cron, or your own worker. Without a runner, jobs stay in the queue. To work without the jobs queue, see Without Payload jobs.The first run happens after the first change, or when you press Regenerate on the Sitemap page.
sitemap-generate job. The job waits jobs.regenerate.delay (5 minutes by default). More changes in that time join the same job.sitemap-status global switches the endpoints to the new files.publish, the changed files then go to their public keys.If the run fails before the switch, it removes the files it stored, and the previous files stay online.
overrideAccess: false, no user). The collection's own read access decides what is public, so members-only or tenant-scoped documents stay out.access: { read: () => true }, or set query: { overrideAccess: true } for that source.tenants option, every tenant's documents end up in one sitemap.Every option is checked when Payload starts. An unknown key, a wrong type or a value out of range stops Payload from starting, with an error that names the option.
| Option | Type | Default | What it does |
|---|---|---|---|
siteUrl | string | ({ locale, req, tenant }) => string | required | Public site address. A function can give each locale or tenant its own domain. See Output. |
sources | SitemapSource[] | [] | What the sitemap lists: collections, static pages and custom URL lists. See Sources. |
output | SitemapOutputOptions | {} | File size, file names, file URLs, hreflang and one index per locale. See Output. |
storage | SitemapStorageOptions | {} | Where the files are stored. See Storage. |
publish | SitemapPublishOptions | Also write every file to a stable public key. See Publish. | |
tenants | boolean | SitemapTenantsOptions | false | One sitemap per tenant for the multi-tenant plugin. See Multi-tenant. |
jobs | false | SitemapJobsOptions | {} | When generation runs. false uses no jobs queue. See Jobs. |
admin | SitemapAdminOptions | {} | Sitemap page, widget and who can use them. See Admin page and widget. |
enabled | boolean | true | false turns the plugin off but keeps its database schema. See below. |
telemetry | boolean | { url? } | true | Anonymous usage telemetry. See Telemetry. |
Each group has its own exported type, such as SitemapCollectionSource, SitemapOutputOptions or SitemapStorageOptions. Your editor shows the docs for each field.
With enabled: false (useful in development):
sources is one array. Each source has a type and writes its own files, named after the source: pages-1.xml, pages-2.xml. The index lists the files in the order of the array.
sources: [
{ type: 'static', entries: [{ url: '/' }, { url: '/contact' }] },
{ type: 'collection', collection: 'pages' },
{ type: 'collection', collection: 'posts', url: '/blog/:slug' },
{ type: 'custom', name: 'catalog', entries: catalogEntries },
]
name is the file name part: letters, digits, - and _. It defaults to the collection slug, or to static.query.where. Only one of those sources may set fields.| Key | Type | Default | What it does |
|---|---|---|---|
collection | string | required | Slug of the collection. |
name | string | the slug | File name part. |
url | string | ({ doc, locale, req, siteUrl, tenant }) => string | null | '/:slug' | URL pattern with :field placeholders, or a function. |
locales | string[] | every locale | Locales to write this collection for. |
lastmod | string | false | ({ doc }) => Date | string | 'updatedAt' | Field with the last change date, false to leave <lastmod> out, or a function. |
changefreq | static value or function | always, hourly, daily, weekly, monthly, yearly or never. | |
priority | static value or function | From 0 to 1. | |
images | (string | { field, url } | fn)[] | fn | Image field paths, functions, or both. See Images. | |
fields | boolean | { exclude, priority, changefreq, position } | false | Add per-document fields. See Sitemap fields. |
query | { where, depth, select, sort, overrideAccess } | Options for reading the documents. See Query. |
{
type: 'collection',
collection: 'products',
url: '/shop/:category.slug/:slug',
lastmod: 'meta.publishedAt',
changefreq: 'daily',
priority: ({ doc }) => (doc.featured ? 1 : 0.6),
images: [{ field: 'gallery.image', url: (image) => `https://img.example.com/${image.filename}` }],
query: { where: { stock: { greater_than: 0 } } },
}
With generated types, doc in every function has the type of that collection.
A url string fills each :field placeholder from the document.
:category.slug reads doc.category.slug. This goes through groups, named tabs and relationships. A relationship placeholder needs depth 1, and the plugin sets it for you.:vendor.slug reads the related document.hasMany list, leaves the document out./ inside a value is kept.:locale is the locale of the URL: /:locale/blog/:slug. It needs localization, or Payload does not start./:{slug}.html. Without braces, :slug.html reads the nested field slug.html.siteUrl.// keeps its host and takes the protocol of siteUrl.Use a function for anything a pattern cannot express. It gets the document, the locale, req, the tenant and the siteUrl of that locale. It can return:
/de/kontakt, which is joined to siteUrl;null, which leaves the document out.query goes to payload.find. Documents are read 250 at a time.
where filters the documents. Drafts are skipped anyway, but a where on _status still applies.depth defaults to 0. It is 1 when images uses field paths or the url pattern has a nested placeholder.select, the plugin adds the fields that the url pattern, lastmod, images, sort and the sitemap fields need.overrideAccess: true reads every document and ignores the collection's read access. Use it only when the collection's access does not describe what is public.query.sort sets the order of the URLs. It defaults to id. Put - in front for descending order: sort: '-publishedAt'.
id, createdAt and updatedAt. Any other field stops Payload from starting, with an error.sort takes only the field names of that collection, so your editor suggests them. Localized fields still pass the type check, but stop Payload from starting.id order.id, so equal values never lose or repeat a document.updatedAt changes when someone saves the document while the run reads. The save queues a new run, which lists the document again.changefreq and priority take a static value, or a function of the document:
priority: ({ doc }) => (doc.featured ? 1 : 0.6),
changefreq: async ({ doc, locale, req }) => (await isOnSale(doc, req)) ? 'daily' : 'monthly',
{ doc, locale, req } and may be async.undefined, the tag is left out for that document.<priority> tag, and a warning is logged. A static value outside that range stops Payload from starting.lastmod works the same way: a field name, false, or a function that returns a date.
Static and custom sources set their tags per entry, so these rules do not apply to them.
images: ['cover', 'hero.image', 'gallery.image', { field: 'layout.media', url: (image) => image.sizes?.large?.url }]
gallery.image reads image from every row of gallery.hasMany, or with several collections in relationTo, give one image per file.url. Pass url to build the URL yourself, for example for an image CDN. Return null to skip an image./, as Payload writes for local files) is resolved against the Payload serverURL. Without serverURL, it is skipped.A function gets { doc, locale, req }, may be async, and returns URLs:
images: ({ doc }) => doc.photos.map((photo) => photo.src)
Field paths and functions can share one array, and the results are merged:
images: ['cover', ({ doc }) => doc.externalPhotos ?? []]
When the array has only functions, depth stays 0, so upload fields come as IDs. Set query.depth if a function needs the upload documents.
Sitemap fields let editors control one document:
exclude) leaves the document out.priority, 0 to 1) and Change frequency (changefreq) override the source value for this document.fields: true
fields: { exclude: true }
fields: { exclude: true, priority: true, position: { after: 'featured' } }
true adds all three. An object adds only the keys set to true. false or no fields adds nothing.sitemapExclude, sitemapPriority and sitemapChangefreq.position takes 'sidebar' (default), 'first', 'last', { after: 'path' } or { before: 'path' }.
meta.description.description.You can place the fields in three ways:
Let the plugin add them. fields: true puts a Sitemap group in the sidebar.
Next to another field, with position:
plugins: [
seoPlugin({ collections: ['pages'], tabbedUI: true }),
sitemap({
siteUrl: 'https://example.com',
sources: [
{
type: 'collection',
collection: 'pages',
fields: { exclude: true, position: { after: 'meta.description' } },
},
],
}),
]
A field from another plugin, such as the meta group of the SEO plugin, exists only when that plugin comes before sitemap in plugins.
Anywhere you like, with the builders from @seshuk/payload-plugin-sitemap/fields. Leave fields out for that collection:
import { sitemapFields } from '@seshuk/payload-plugin-sitemap/fields'
seoPlugin({
collections: ['pages'],
fields: ({ defaultFields }) => [...defaultFields, ...sitemapFields()],
})
sitemapFields({ exclude: true }) picks the fields. sitemapExcludeField(), sitemapPriorityField() and sitemapChangefreqField() give one field each.
The plugin always reads fields marked with custom: { sitemap: 'exclude' | 'priority' | 'changefreq' }, wherever they are in the collection. The builders set this marker. If a collection already has marked fields, adding fields to its source stops Payload from starting, with an error.
{ type: 'static', entries: [{ url: '/', priority: 1, changefreq: 'daily' }, { url: '/contact' }, { url: 'https://shop.example.com/' }] }
url that starts with / or has no scheme is joined to siteUrl. An absolute URL is kept.static-1.xml, or to <name>-1.xml when you set name.To vary the entries by locale, pass a function. It is called once per locale, and the same url from two locales is written once:
{ type: 'static', entries: ({ locale }) => [{ url: `/${locale}` }, { url: `/${locale}/contact` }] }
{
type: 'custom',
name: 'catalog',
locales: ['en', 'de'],
entries: async function* ({ locale, req, siteUrl }) {
const categories = await req.payload.find({ collection: 'categories', limit: 0, locale, req })
for (const category of categories.docs) {
yield { url: `/catalog/${category.slug}`, changefreq: 'weekly' }
}
},
}
name is required.entries is called once per locale in locales (every locale by default). It can return an array, a promise of an array, or an async generator for long lists.url is joined to siteUrl. An entry with a scheme other than http(s) is skipped with a warning.jobs.regenerate.collections, so changes there queue a run too.| Key | Type | Default | What it does |
|---|---|---|---|
maxUrlsPerFile | number | 50000 | URLs per file. Files also roll over before 50 MB. |
filename | ({ kind, locale, part, source, tenant }) => string | see File names | Name of each file. May contain folders. |
fileUrl | ({ filename, locale, siteUrl, tenant }) => string | ${siteUrl}/sitemaps/${filename} | Public URL of a child sitemap, written into the index. |
hreflang | boolean | true | Add alternates and x-default when there is more than one locale. |
splitLocales | boolean | false | Write one index per locale (sitemap-de.xml, de-pages-1.xml). |
With localization on, every URL is written once per locale. Each one gets xhtml:link alternates for the other locales and an x-default that points to the default locale. Alternates are written only when a page has at least two language versions.
For one domain per locale, pass a function as siteUrl:
sitemap({
siteUrl: ({ locale }) => (locale === 'de' ? 'https://example.de' : 'https://example.com'),
output: { splitLocales: true },
// ...
})
The function also gets req and may be async, so the address can come from a global or a tenant:
siteUrl: async ({ req }) => (await req.payload.findGlobal({ slug: 'settings', req })).siteUrl,
tenants) at the start of each run.splitLocales, /api/sitemap.xml?locale=de returns the index for that locale.filename gets:
kind: index or file;locale: only with splitLocales;tenant: only with tenants;source and part (from 1): only for a child file.The default names are sitemap[-<tenant id>][-<locale>].xml for an index and [<tenant id>-][<locale>-]<source>-<part>.xml for a file.
output: {
splitLocales: true,
filename: ({ kind, locale, part, source }) =>
kind === 'index' ? `${locale}/sitemap.xml` : `${locale}/${source}-${part}.xml`,
}
Rules for names:
/ for folders. Each part of the path uses letters, digits, ., - and _. The name ends in .xml./api/sitemaps/en/pages-1.xml. /api/sitemap.xml always returns the index, whatever its name./ in upload file names, so the upload collection replaces / with _: en_pages-1.3f2a9c1b7e4d.xml. A custom storage.upload gets the name with its folders: en/pages-1.3f2a9c1b7e4d.xml.With @payloadcms/plugin-multi-tenant, turn on tenants and build siteUrl from the tenant document:
sitemap({
siteUrl: ({ tenant }) => `https://${tenant?.domain}`,
sources: [
{ type: 'collection', collection: 'pages' },
{ type: 'collection', collection: 'posts', url: '/blog/:slug' },
],
tenants: true,
})
| Key | Type | Default | What it does |
|---|---|---|---|
collection | string | 'tenants' | Slug of the tenants collection. |
field | string | 'tenant' | Name of the tenant relationship field on documents. |
where | Where | Only tenants that match get a sitemap, for example { active: { equals: true } }. |
true uses the multi-tenant plugin's defaults.
where. If the tenants collection has drafts, draft tenants are skipped too.siteUrl with { locale, req, tenant } and writes a separate index and files.sitemap-<id>.xml, <id>-pages-1.xml. With output.splitLocales, the locale follows the id: sitemap-<id>-de.xml.entries, a collection url function, output.filename and output.fileUrl also get tenant, so they can return different URLs per tenant./api/sitemap.xml?tenant=<id>. Without a tenant, the endpoint returns 404.tenant to sitemapProxy to pick the tenant from the host name. See Serve on your site domain.- and _. The default ids of every database adapter do.eu with a source news-pages and tenant eu-news with the pages collection both give eu-news-pages-1.xml. The run then fails before it writes anything.field as a relationship to the tenants collection.tenants on adds a tenant column to the files collection. On SQL databases, create a migration.| Key | Type | Default | What it does |
|---|---|---|---|
collection | CollectionOverride | { slug: 'sitemap-files' } | Changes to the files collection: slug, access, admin, upload, and fields({ defaultFields }). |
upload | ({ body, contentType, filename, req }) => { url } | Upload the files yourself. The files collection then keeps only the file list. | |
delete | ({ filename, req, url }) => unknown | Delete a file from your storage when a run no longer needs it. Needs upload. |
By default, files go into the sitemap-files upload collection.
<uuid>/posts-1.3f2a9c1b7e4d-original.xml.posts-1.xml). The endpoints send the file themselves.In Payload 4, configure your storage adapter for it in the top-level storage list, like any other upload collection:
export default buildConfig({
// ...
storage: [
s3Storage({
collections: { media: true, 'sitemap-files': true },
// ...
}),
],
})
You rarely need to change it. collection takes any collection key, and each key you pass replaces the plugin's value. Common cases:
slug: the name sitemap-files is taken, or does not fit your naming.admin: show the file list in the admin panel. It is hidden by default.access: choose who can read the file list through the API. By default, the people who can open the admin page.upload: change the upload settings, for example staticDir, the folder on disk when no storage adapter handles the collection.fields: gets the plugin's fields and returns the new list.storage: {
collection: {
slug: 'seo-files',
admin: { hidden: false, useAsTitle: 'name' },
},
}
To keep the files out of Payload, pass upload. Use it for your own bucket, Bunny Storage or a folder on disk. The files collection then has no uploads and only keeps the file list. collection still works, except collection.upload.
storage: {
upload: async ({ body, contentType, filename }) => {
await bucket.put(`seo/${filename}`, body, { contentType })
return { url: `https://cdn.example.com/seo/${filename}` }
},
delete: async ({ filename }) => {
await bucket.delete(`seo/${filename}`)
},
}
upload
Buffer, with its name and content type. It returns the URL where the file can be read.serverURL. Without serverURL, the run fails.filename ends with a hash of the content (posts-1.3f2a9c1b7e4d.xml), so each version gets a new name and nothing is overwritten.output.filename are kept: en/posts-1.3f2a9c1b7e4d.xml.upload throws or returns no url, the run fails and the previous files stay listed.delete is optional. It gets the same filename and the url that upload returned.
posts-3.xml after the posts fit in two files.could not delete the files of an earlier failed run, and the previous files stay online. Fix the database error and run again.delete throws, the error is logged and the run goes on.delete, old files stay in your storage, but the endpoints stop serving them.uploadA file whose content did not change is not uploaded again and keeps its URL. So after you move to upload, delete the documents of the files collection once and press Regenerate. Otherwise, unchanged files keep their old collection URL:
await payload.delete({ collection: 'sitemap-files', where: { id: { exists: true } }, overrideAccess: true })
Writing to disk works the same way, as long as something serves the folder:
import { mkdir, rm, writeFile } from 'node:fs/promises'
import { dirname } from 'node:path'
storage: {
upload: async ({ body, filename }) => {
await mkdir(dirname(`public/seo/${filename}`), { recursive: true })
await writeFile(`public/seo/${filename}`, body)
return { url: `https://example.com/seo/${filename}` }
},
delete: ({ filename }) => rm(`public/seo/${filename}`, { force: true }),
}
storage keeps hashed versions that only the endpoints know. To put the files at stable public keys, add publish and point output.fileUrl at the same place. For example, https://cdn.example.com/sitemaps/posts-1.xml on a CDN:
sitemap({
// ...
output: { fileUrl: ({ filename }) => `https://cdn.example.com/sitemaps/${filename}` },
publish: {
put: ({ body, contentType, filename }) => bucket.put(`sitemaps/${filename}`, body, { contentType }),
delete: ({ filename }) => bucket.delete(`sitemaps/${filename}`),
},
})
| Key | Type | Default | What it does |
|---|---|---|---|
put | ({ body, contentType, filename, req }) => unknown | Write one file to its public key. filename is the plain name, no hash. | |
delete | ({ filename, req }) => unknown | Remove a public file the newest run no longer writes. |
publish needs output.fileUrl, because the index must point to the published files. Without it, Payload does not start.put for every changed child file first, then for every changed index. A file whose content did not change is not written again.delete for each name it no longer writes. A delete error is logged and the run goes on. Without delete, those files stay, but no index lists them.put failsposts-3.xml, until the next successful run removes them.| Key | Type | Default | What it does |
|---|---|---|---|
regenerate | false | { delay, collections, globals } | { delay: 300000 } | Queue a run after changes. collections and globals add more triggers, for data your sources read. |
schedule | string | Cron for scheduled runs, for example 0 3 * * *. Your job runner must handle schedules. | |
queue | string | 'default' | Jobs queue for the task. |
Every run takes a lock in the hidden sitemap-locks collection, whether it comes from a job, the endpoint or generateSitemap.
sitemap: a sitemap run is already in progress. In that case, generateSitemap(req) throws this error. With jobs: false, POST /api/sitemap/generate answers 409. Try again later.The job runner never runs two sitemap jobs in parallel. A sitemap job that finds the lock busy fails and retries with growing waits: 30 seconds, then 1, 2, 4 and 8 minutes. That is 6 attempts (1 + 5 retries) in about 15 minutes, so the job usually runs after the other run ends.
If the lock stays busy through all 6 attempts, the job fails for good. The next change or scheduled run queues a new one.
Set jobs: false when your host has no job runner. The plugin then adds no task, no hooks and no schedule. Payload adds no payload-jobs collection unless something else needs it.
Start runs yourself:
POST /api/sitemap/generate. The request runs the whole generation. It answers 200 { files, urls }, 409 while another run holds the lock, or 500 { message } when the run fails.generateSitemap(req) from your own cron or queue.The run has to finish within one request, so check your platform's limits:
output.maxUrlsPerFile to keep each file small in memory.On serverless hosts, prefer the jobs queue for large sites.
| Key | Type | Default | What it does |
|---|---|---|---|
access | ({ req }) => boolean | users of admin.user | Who can open the Sitemap page and widget and start a run. Replaces the default check. |
view | boolean | true | Add the Sitemap page at /admin/sitemap and its link in the nav. |
widget | boolean | true | Add the Sitemap widget to the dashboard "Add +" list. |
access see the page, the nav link and the widget./admin/sitemap.access with a request that holds only the user, with the fields that user may read.access on the user, not on headers, cookies or fields the user cannot read. Otherwise the link and the page may disagree.The file table works like a Payload collection list:
tenants, a Locale select with output.splitLocales, and a Source select with more than one source. Tenants show by title, from the useAsTitle field of the tenants collection.defaultLayout, so the widget appears only where someone adds it.view: false), there is no link.Before the first run, the page and the widget show "Not generated yet" and a Generate button.
| Method | Path | Access | What it does |
|---|---|---|---|
| GET | /api/sitemap.xml | public | The sitemap index. Takes ?locale= with output.splitLocales and ?tenant= with tenants. |
| GET | /api/sitemaps/:filename+ | public | A child sitemap, by its name with folders. With ?tenant=, files of other tenants return 404. |
| GET | /api/sitemap/status | access | Last run, error, URL and file counts, and run state. |
| GET | /api/sitemap/files | access | Live files, index files first. See the query parameters below. |
| POST | /api/sitemap/generate | access | Start a run. With jobs, 202 { id }. With jobs: false, see Without Payload jobs. |
GET /api/sitemap/files takes:
?page= and ?limit= (1 to 100, default 100);?search=, ?tenant=, ?locale= and ?source=;?sort= with filename, locale, source, urls, size or lastmod. Put - first for descending order;?groupBy= with tenant, locale or source. The answer then has groups, with the first page of each. Add ?group= for more pages of one group.Cache-Control: public, max-age=300 and an ETag from the content hash.If-None-Match gets 304 without a body.502.Every endpoint carries an OpenAPI operation in custom.openapi. With @seshuk/payload-plugin-openapi installed, they show up in your spec under the Sitemap tag. Without it, this metadata does nothing.
Search engines expect /sitemap.xml on the site itself. The default fileUrl also points child files to /sitemaps/<file> on the site, so the site must answer both paths.
Rewrites are enough:
// next.config.ts
export default withPayload({
async rewrites() {
return [
{ source: '/sitemap.xml', destination: '/api/sitemap.xml' },
{ source: '/sitemaps/:path*', destination: '/api/sitemaps/:path*' },
]
},
})
Rewrites cannot pass ?tenant= or ?locale= to Payload: Next.js does not give the query of a rewrite destination to the API route. When the app serves several domains, one per locale or one per tenant, use sitemapProxy route handlers instead, with serverUrl set to the address of the app itself.
TanStack Start has no rewrites. Add the TanStack Start routes below, with serverUrl set to the address of the app itself.
sitemapProxy turns a site request into an API request and passes the file back.
If-None-Match and passes a 304 back.502. A 404 from the API stays 404.fetch, Request and Response, so it works in any framework that speaks web standards.With Next.js route handlers:
// app/sitemap.xml/route.ts and app/sitemaps/[...path]/route.ts
import { sitemapProxy } from '@seshuk/payload-plugin-sitemap/proxy'
export const GET = sitemapProxy({ serverUrl: 'https://cms.example.com' })
With TanStack Start server routes:
// src/app/sitemap[.]xml.ts, and src/app/sitemaps.$.ts with the path '/sitemaps/$'
import { sitemapProxy } from '@seshuk/payload-plugin-sitemap/proxy'
import { createFileRoute } from '@tanstack/react-router'
const proxy = sitemapProxy({ serverUrl: 'https://cms.example.com' })
export const Route = createFileRoute('/sitemap.xml')({
server: { handlers: { GET: ({ request }) => proxy(request) } },
})
With Nuxt:
// server/routes/sitemap.xml.ts and server/routes/sitemaps/[...path].ts
import { sitemapProxy } from '@seshuk/payload-plugin-sitemap/proxy'
const proxy = sitemapProxy({ serverUrl: 'https://cms.example.com' })
export default defineEventHandler((event) => proxy(toWebRequest(event)))
When one site serves several domains, tell the proxy which index each domain gets. This also works when Payload runs in the same app: point serverUrl at the app itself.
locale: (request) => code picks the locale for /sitemap.xml. Use it with splitLocales.tenant: (request) => id picks the tenant. Use it with tenants. Child files of other tenants then return 404, and so does a request with no tenant.const locales: Record<string, string> = { 'example.com': 'en', 'example.de': 'de' }
export const GET = sitemapProxy({
serverUrl: 'https://cms.example.com',
locale: (request) => locales[new URL(request.url).hostname],
})
const tenantIds: Record<string, string> = { 'gold.example.com': '1', 'blue.example.com': '2' }
export const GET = sitemapProxy({
serverUrl: 'https://cms.example.com',
tenant: (request) => tenantIds[new URL(request.url).hostname],
})
Make siteUrl return the same domain for that locale or tenant. The index then points its child files back to the same domain, as the sitemap protocol asks.
In Next.js, add app/robots.ts to the site:
// app/robots.ts
import type { MetadataRoute } from 'next'
export default function robots(): MetadataRoute.Robots {
if (process.env.VERCEL_ENV === 'preview') {
return { rules: { userAgent: '*', disallow: '/' } }
}
return {
rules: {
userAgent: '*',
allow: ['/', '/api/sitemap.xml', '/api/sitemaps/', '/api/media/file/'],
disallow: ['/admin', '/api'],
},
sitemap: 'https://example.com/sitemap.xml',
}
}
This example is for a site that shares its host with Payload:
Disallow lines keep the admin panel and the API out.Allow lines keep the sitemap routes and the upload files open, so crawlers can read the images that the sitemap lists. Add one /api/<slug>/file/ line per upload collection.Allow: /api/media/file/ wins over Disallow: /api.cms.example.com, leave out the /api and /admin lines.VERCEL_ENV check keeps preview deployments out of search engines. On another host, check your own environment variable.In TanStack Start, return the same rules as text from a server route:
// src/app/robots[.]txt.ts
import { createFileRoute } from '@tanstack/react-router'
const robots = `User-agent: *
Allow: /
Allow: /api/sitemap.xml
Allow: /api/sitemaps/
Allow: /api/media/file/
Disallow: /admin
Disallow: /api
Sitemap: https://example.com/sitemap.xml
`
export const Route = createFileRoute('/robots.txt')({
server: { handlers: { GET: () => new Response(robots, { headers: { 'Content-Type': 'text/plain' } }) } },
})
Disallow stops crawling, not indexing. A blocked URL can still appear in search results if other sites link to it. To keep a page out of the index, use a noindex meta tag.
Two functions start a run from your own code: a hook, an endpoint, a cron or a script. Both take a Payload request (req). In a script, build one with await createPayloadRequest({ payload }) from payload.
import { generateSitemap, queueSitemap } from '@seshuk/payload-plugin-sitemap'
| Function | What it does | Use it when |
|---|---|---|
queueSitemap(req, delay?) | Puts a run into the jobs queue and returns the job id. The job runner does the work. | You use the jobs queue (default). |
generateSitemap(req) | Runs the whole generation now, in this process, and returns the written files. | jobs: false, scripts and tests. |
// After a bulk import: run in one minute
await queueSitemap(req, 60_000)
// In a script: run now
const files = await generateSitemap(req)
queueSitemap
delay is in milliseconds, 0 by default: the job runs on the next pass of the job runner.delay ends sooner.jobs: false, it throws. Call generateSitemap instead.generateSitemap
sitemap: a sitemap run is already in progress.queueSitemap instead.Generation pages through each collection 250 documents at a time. It writes each file as soon as the file is full, so memory stays flat however many documents you have.
pnpm test:stress seeds SQLite with 365,000 URLs in all: 120,000 pages in two locales, 60,000 posts, a source with 30,000 URLs per locale and 5,000 static entries. With the index below, one run takes:
Most of the time goes to the database adapter reading documents, not to writing XML.
A collection with drafts costs one extra read per 250 documents, to get the status in each locale. On Payload 4, filtering the status in the query instead makes the run about four times slower. The cost is memory: with the filter in the query, the peak was 368 MB instead of 468 MB, mostly short-lived objects that garbage collection frees.
Each file is one document in the files collection, so the number of tenants has no fixed limit. On SQLite with 10,000 tenants and 40,000 files written to local disk:
Uploads to remote storage add their own time for each changed file. A change in a collection without the tenant field, such as shared posts, changes that file and the index of every tenant. All of them are then uploaded again.
Payload's SQL adapters (SQLite and Postgres) create the <collection>_locales table of a localized collection without an index on _parent_id. Each read of that collection then scans the whole locales table once per document, so generation time grows with the square of the collection size. The CI-size stress run (12,000 pages, 8,000 posts) takes 47.8 seconds without the index and 1.9 seconds with it.
For a large localized collection, add a migration that creates the index:
CREATE INDEX IF NOT EXISTS pages_locales_parent_id_idx ON pages_locales (_parent_id);
The plugin sends a small anonymous usage report, at most once a day. It shows the maintainer which versions and features people use. Telemetry is on by default. On the first run, the plugin logs how to turn it off.
sha256(payload.secret + source). The source is the git remote URL, the app's package.json name, serverURL or the working directory. Only the hash leaves your server.features: booleans only, listed below.The plugin never sends secrets, IP addresses, keys, file names, URLs or collection names.
| Flag | Meaning |
|---|---|
siteUrlFunction | siteUrl is a function |
staticSources | A static source is set |
customSources | A custom source is set |
collectionUrlFunction | A collection source builds its url with a function |
collectionImages | A collection source sets images |
collectionFields | A collection source adds the sitemap fields |
collectionQuery | A collection source sets query |
collectionSort | A collection source sets query.sort |
outputFilename | output.filename is set |
outputFileUrl | output.fileUrl is set |
outputHreflang | hreflang alternates are on |
outputSplitLocales | output.splitLocales is on |
storageCollection | storage.collection is set |
storageUpload | Files are stored through storage.upload |
storageDelete | storage.delete is set |
publish | publish is set |
publishDelete | publish.delete is set |
jobs | Runs go through the jobs queue |
jobsRegenerate | Changes queue a run |
jobsRegenerateTriggers | jobs.regenerate lists extra collections or globals |
jobsSchedule | jobs.schedule is set |
adminAccess | admin.access replaces the default check |
adminView | The Sitemap page and nav link are on |
adminWidget | The dashboard widget is on |
tenants | tenants is on |
Telemetry is off when any of these is true:
telemetry: false in the plugin options or in the Payload config;enabled: false in the plugin options;DO_NOT_TRACK or SITEMAP_TELEMETRY_DISABLED is set to a truthy value;CI is set, or NODE_ENV is test.To send reports to your own collector, pass telemetry: { url: 'https://telemetry.example.com/v1/collect' }. Reports never block startup or throw errors, and they time out after 2 seconds.
Bug reports, feature requests and questions go to GitHub Issues. For Payload itself, see the Payload docs and Discord.
MIT. See LICENSE.
Built by Maxim Seshuk for the Payload community.
If this plugin saves you time, you can buy me a coffee ☕
Topics
seo
SEO fields, settings global and automatic redirects for Payload, with Next.js metadata, sitemap and robots helpers
75303/wk3v3
payload seo analyzer
Offline on-page SEO analysis, admin dashboard, sitemaps and JSON-LD for Payload 3 and Next.js sites
72880/wk17v3
payload plugin structured data
JSON-LD structured data for Payload pages, editable from admin settings and per-document overrides
6943/wk1v3
sitemap
Chunked, lazily cached XML sitemaps with hook-driven invalidation and robots.txt helpers
62156/wk16v3
payload plugin seo jsonld
JSON-LD builders for Payload v3 shops: Product, BreadcrumbList, ItemList, WebSite and Organization
617/wk1v3
seo
Locale-aware SEO fields, metadata resolution, robots, exact redirects and sitemap helpers
6030/wk0v4