Scans your storage and database to report orphaned files, documents whose files are missing, and documents nothing references. Findings are stored in two added collections, and only items you mark for deletion are removed, after a second check. It supports S3-compatible storage, R2, Google Cloud Storage, Azure, Bunny, uploadthing, Vercel Blob and local disk, and needs Payload 4 with Postgres, SQLite or MongoDB for usage detection.
Housekeeping for Payload: find orphaned files, broken uploads and documents nothing references, then delete only what you approve.
Installation
npm i @seshuk/payload-plugin-janitor7
Stars
0
Forks
4
Open Issues
3 days ago
Last Updated
10
Weekly Downloads
v0.1.0
npm Version
1.6 MB
Unpacked Size
0
Dependencies
7+7 since Oct 11
| Date | Stars |
|---|---|
| Dec 6, 2026 | 7 |
| Dec 5, 2026 | 7 |
| Dec 4, 2026 | 7 |
| Dec 3, 2026 | 7 |
| Dec 2, 2026 | 7 |
| Dec 1, 2026 | 7 |
| Nov 30, 2026 | 7 |
| Nov 29, 2026 | 7 |
| Nov 28, 2026 | 7 |
| Nov 27, 2026 | 7 |
| Nov 26, 2026 | 7 |
| Nov 25, 2026 | 7 |
| Nov 24, 2026 | 7 |
| Nov 23, 2026 | 7 |
| Nov 22, 2026 | 7 |
| Nov 21, 2026 | 7 |
| Nov 20, 2026 | 7 |
| Nov 19, 2026 | 7 |
| Nov 18, 2026 | 7 |
| Nov 17, 2026 | 7 |
| Nov 16, 2026 | 7 |
| Nov 15, 2026 | 7 |
| Nov 14, 2026 | 7 |
| Nov 13, 2026 | 7 |
| Nov 12, 2026 | 7 |
| Nov 11, 2026 | 7 |
| Nov 10, 2026 | 7 |
| Nov 9, 2026 | 7 |
| Nov 8, 2026 | 7 |
| 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 | 5 |
| Oct 18, 2026 | 5 |
| Oct 17, 2026 | 3 |
| Oct 16, 2026 | 3 |
| Oct 15, 2026 | 2 |
| Oct 14, 2026 | 0 |
| Oct 13, 2026 | 0 |
| Oct 12, 2026 | 0 |
| Oct 11, 2026 | 0 |
11−43 since Oct 18
| Date | Weekly downloads |
|---|---|
| Dec 6, 2026 | 11 |
| Dec 5, 2026 | 13 |
| Dec 4, 2026 | 14 |
| Dec 3, 2026 | 18 |
| Dec 2, 2026 | 17 |
| Dec 1, 2026 | 20 |
| Nov 30, 2026 | 22 |
| Nov 29, 2026 | 18 |
| Nov 28, 2026 | 15 |
| Nov 27, 2026 | 14 |
| Nov 26, 2026 | 11 |
| Nov 25, 2026 | 7 |
| Nov 24, 2026 | 6 |
| Nov 23, 2026 | 4 |
| Nov 22, 2026 | 10 |
| Nov 21, 2026 | 11 |
| Nov 20, 2026 | 17 |
| Nov 19, 2026 | 18 |
| Nov 18, 2026 | 26 |
| Nov 17, 2026 | 24 |
| Nov 16, 2026 | 25 |
| Nov 15, 2026 | 23 |
| Nov 14, 2026 | 22 |
| Nov 13, 2026 | 18 |
| Nov 12, 2026 | 18 |
| Nov 11, 2026 | 11 |
| Nov 10, 2026 | 17 |
| Nov 9, 2026 | 28 |
| Nov 8, 2026 | 28 |
| Nov 7, 2026 | 32 |
| Nov 6, 2026 | 32 |
| Nov 5, 2026 | 37 |
| Nov 4, 2026 | 36 |
| Nov 3, 2026 | 38 |
| Nov 2, 2026 | 36 |
| Nov 1, 2026 | 47 |
| Oct 31, 2026 | 178 |
| Oct 30, 2026 | 185 |
| Oct 29, 2026 | 178 |
| Oct 28, 2026 | 177 |
| Oct 27, 2026 | 174 |
| Oct 26, 2026 | 178 |
| Oct 25, 2026 | 175 |
| Oct 24, 2026 | 94 |
| Oct 23, 2026 | 85 |
| Oct 22, 2026 | 85 |
| Oct 21, 2026 | 85 |
| Oct 20, 2026 | 80 |
| Oct 19, 2026 | 66 |
| Oct 18, 2026 | 54 |
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/1419092898-root)<a href="https://payloaddirectory.dev/plugins/1419092898-root"><img src="https://payloaddirectory.dev/badge/1419092898-root.svg" alt="Payload Directory"></a>README
Housekeeping for Payload: find orphaned files, missing files and unused documents by comparing your storage with your database.
_rels, JSON, blocks, rich text, globals and versions. Unsure means used.The dashboard widget shows what the last scan found and how much space you can free:

The findings list, with the menu that starts a scan or deletes the approved findings:

A finding explains what was found and lets you choose what to do with it:

The usage panel on an upload document lists every place that references it:

A run record shows what a scan found in each collection:

| Plugin | Payload | Node.js | Install |
|---|---|---|---|
| 1.x | 4 | 24.22.1+ | @seshuk/payload-plugin-janitor@beta |
| 0.x | 3 | 22+ | @seshuk/payload-plugin-janitor@0 |
beta npm tag. Payload 4 is published under beta too.4.0.0-beta.4 or later and Next.js 16.4 or later. Canary builds are not supported.Once 1.0.0 is stable, latest moves to 1.x. 0.x stays available as @seshuk/payload-plugin-janitor@0 or under the
latest-0 tag. It gets only critical and high-severity security fixes. See SECURITY.md.
# Payload 4
pnpm add @seshuk/payload-plugin-janitor@beta
# Payload 3
pnpm add @seshuk/payload-plugin-janitor@0
import { s3Storage } from '@payloadcms/storage-s3'
import { janitor } from '@seshuk/payload-plugin-janitor'
import { s3Adapter } from '@seshuk/payload-plugin-janitor/s3'
import { buildConfig } from 'payload'
export default buildConfig({
storage: [
s3Storage({
bucket: 'assets',
collections: { media: { prefix: 'media' } },
config: { region: 'eu-central-1' },
}),
],
plugins: [
janitor({
collections: { media: true },
storage: s3Adapter({ bucket: 'assets', config: { region: 'eu-central-1' } }),
}),
],
})
Only the collections you list under collections are scanned, guarded or get a panel. media: true turns on
everything the collection can have: all three checks, the usage panel and the delete guard.
Storage plugins go in storage, as above, or in plugins before janitor. See
Plugin order and prefix.
The plugin adds two collections to the admin, Janitor findings and Janitor runs, in the System nav group.
payload generate:importmap, so the admin panel can find the plugin's menu, panel and widget.Nothing is deleted before step 4.
A scan compares your storage with your database and reports three kinds of findings. In this README, an ordinary collection is any collection that is not an upload collection.
| Kind | What it means | Example | Can be purged? |
|---|---|---|---|
orphan | A file in storage that no document holds. | media/old-banner.jpg is in the bucket, but no document names it. | Yes. The purge deletes the file from storage. |
missing | A document whose file is not in storage. | A media document names photo.jpg, but the bucket has no such file. | Never. Re-upload the file or delete the document yourself. |
unused | A document that nothing references, in an upload or ordinary collection. | An image no page uses, or a tag no post has. | Yes. The purge deletes the document through Payload, or moves it to the trash. |
orphan and missing need a storage adapter. unused works on every listed collection.
A run goes like this:
minAge (24 hours by default) is left out.found). You mark it To delete (delete) or Keep (keep).delete and checks it again right before it acts. See
What a purge checks.deleted. A finding that fails
the check goes to keep, with a note that says why.orphans lists the collection's storage under its prefix. It reports every object whose full key no document
holds.
original.filename), image variants (variants.*.filename), trashed documents and draft
versions.a/photo.jpg
counts as holding media/a/photo.jpg. This can hide an orphan, but it never reports a used file.missing reports every document whose key was not in that listing.
unused builds a reverse index of references to the collection's documents. It reports every document with
none.
missing only, not also as unused.unused findings for that collection and logs this warning:
janitor: usage of "x" could not be read reliably, so no unused findings were written for it.A finding's key (objectKey) is the storage key (media/photo.jpg) for orphans, missing files and unused uploads.
For a document of an ordinary collection, it is <slug>/<id>, for example tags/12. How the plugin builds storage
keys is described under Document keys.
Orphans. An orphan is deleted only if all of these are true:
minAge.Right before the delete, the plugin looks up each orphan in storage again on its own (list with keys: [key]), so
an object written again since the scan is kept. The adapter's delete removes the object.
Unused documents. An unused document is deleted only if all of these are true:
createdAt equals the finding's uploadedAt (shown as
Created at). An id that a newer document reused is never deleted.tenants, it still belongs to the tenants the finding names. See Multi-tenant.updatedAt is older than minAge.If the collection has Payload's trash: true, the document moves to the trash. Otherwise it is deleted, and Payload
and your storage plugin remove its file as on any other delete.
Missing files. A missing finding is never acted on. You fix it yourself: re-upload the file or delete the
document.
What happens to each finding after a purge is listed under Purge results.
| Option | Type | Default | What it does |
|---|---|---|---|
enabled | boolean | true | false switches the plugin off but keeps its schema. See below. |
collections | Record<slug, boolean | object> | required | The collections to scan and guard, by slug. false skips an entry. See Per collection. |
storage | StorageAdapter | none | Listing and deletion for every upload collection without its own storage. See Storage adapters. |
minAge | number | 86400 (24 hours) | Seconds. Anything younger is never reported or deleted. See below. |
jobs | false | JobsOptions | false | Run scans and purges inside the request, or queue them as Payload jobs. See Starting runs. |
access | JanitorAccessOptions | see Access | Who may read, approve, scan and purge. See Access. |
tenants | boolean | { collection?, field? } | false | Findings per tenant, for @payloadcms/plugin-multi-tenant. See Multi-tenant. |
references.ignoreTables | string[] | [] | Tables or collections whose references do not keep a document. See Reference options. |
references.text | boolean | false | Also match ids stored whole in text columns. See Reference options. |
references.versions | 'used' | 'unused' | 'used' | Whether a reference in an old version keeps a document. See Reference options. |
admin | false | { group?, widget? } | { group: 'System', widget: true } | Findings list menu, nav group and dashboard widget. See Admin UI. |
endpoints | false | { path? } | { path: '/janitor' } | REST routes for scan, purge and the usage panel. See REST endpoints. |
overrides | { findings?, runs? } | none | Changes to the plugin's two collections. See Overrides. |
telemetry | boolean | { url? } | true | Anonymous usage telemetry. See Telemetry. |
The options types are exported (JanitorPluginOptions, JanitorCollectionOptions, JobsOptions,
JanitorAccessOptions, JanitorTenantsOptions), so your editor shows the docs for each field.
minAge. Objects and documents younger than this are never reported or deleted, because an upload and its
database row are not written in one step. The value is in seconds and must be 0 or at least 3600. A value from
1 to 3599 is most likely meant as hours, so startup rejects it.enabled: false. The plugin is off, but both collections and the janitor-run task stay, so the database
schema does not change and no migration drops the findings. The task does nothing. The plugin adds no routes,
panels, delete guards, admin UI or startup checks, and sends no telemetry. This is handy per environment:janitor({ enabled: process.env.JANITOR !== 'off', collections: { media: true }, storage })
collections.<slug> takes true, false or an object:
| Option | Type | Default | What it does |
|---|---|---|---|
report | boolean | Check[] | true | Which checks a scan runs. false scans nothing but keeps the panel and the guard. See below. |
usagePanel | boolean | UsagePanelOptions | true (false with endpoints: false) | The "where is this used" panel on the edit view. See Usage panel. |
blockDelete | boolean | true | Refuse a delete while something still references the document. See Delete guard. |
storage | StorageAdapter | the top-level storage | Listing and deletion for this collection's files. Upload collections only. |
prefix | string | the storage plugin's prefix field default, or '' | Key prefix inside that storage, without slashes at either end. Upload collections only. See Plugin order and prefix. |
compositePrefixes | boolean | false | The storage plugin runs with useCompositePrefixes. Needs prefix. Upload collections only. See Plugin order and prefix. |
The checks are 'orphans', 'missing' and 'unused'. What report: true (or no report) means depends on the
collection:
| Collection | report: true means |
|---|---|
| upload with a storage | ['orphans', 'missing', 'unused'] |
| upload without a storage | ['unused'], with a note in the log |
| ordinary collection | ['unused'] |
To leave a check out, use an explicit list. For example, use report: ['orphans', 'unused'] for a bucket whose
lifecycle rules delete files on purpose.
Trash on purge is not an option. It follows the collection's own Payload trash setting.
There is no defaults key. To share settings between collections, reuse a JavaScript object:
const media = { usagePanel: { position: { after: 'alt' }, limit: 5 } } as const
janitor({ collections: { images: media, videos: media }, storage })
overrides.findings and overrides.runs take Payload collection settings:
access, admin and labels are merged one level deep.hooks are added after the plugin's own hooks of the same kind.slug renames the collection. Every relation, query and ignored table follows it.fields is a function that gets the default fields.janitor({
collections: { media: true },
overrides: {
findings: {
slug: 'cleanup-findings',
admin: { defaultColumns: ['objectKey', 'kind', 'status', 'ticket'] },
fields: ({ defaultFields }) => [...defaultFields, { name: 'ticket', type: 'text' }],
},
runs: { slug: 'cleanup-runs', labels: { plural: 'Cleanup runs', singular: 'Cleanup run' } },
},
})
Keep the fields the plugin reads and writes. If you remove one of them, scans and purges break.
With tenants, the plugin adds the tenant scope to the findings read, update and delete access. If you override
one of these in overrides.findings.access, your function replaces the tenant scope for that action. Add the scope
yourself if you still need it.
Payload's storage plugins can upload and delete files, but none of them can list a bucket. That is why orphans and
missing need an adapter from this plugin. Each adapter has its own entry point, so only the SDK you use is loaded.
Each one takes a client or binding you have already built.
| Storage | Adapter | Import |
|---|---|---|
@payloadcms/storage-s3, and any S3-compatible service (MinIO, Spaces, B2, R2) | s3Adapter | @seshuk/payload-plugin-janitor/s3 |
@payloadcms/storage-r2, Cloudflare R2 as a Workers binding | r2Adapter | @seshuk/payload-plugin-janitor/r2 |
@payloadcms/storage-gcs | gcsAdapter | @seshuk/payload-plugin-janitor/gcs |
@payloadcms/storage-azure | azureAdapter | @seshuk/payload-plugin-janitor/azure |
@seshuk/payload-storage-bunny | bunnyAdapter | @seshuk/payload-plugin-janitor/bunny |
@payloadcms/storage-uploadthing | uploadthingAdapter | @seshuk/payload-plugin-janitor/uploadthing |
@payloadcms/storage-vercel-blob | vercelBlobAdapter | @seshuk/payload-plugin-janitor/vercelBlob |
Payload's own disk storage (staticDir) | localAdapter | @seshuk/payload-plugin-janitor/local |
import { S3Client } from '@aws-sdk/client-s3'
import { BlobServiceClient } from '@azure/storage-blob'
import { Storage } from '@google-cloud/storage'
import { del, list } from '@vercel/blob'
import { UTApi } from 'uploadthing/server'
s3Adapter({ bucket: 'assets', config: { region: 'eu-central-1' } })
s3Adapter({ bucket: 'assets', config: { region: 'auto', endpoint: 'https://<account>.r2.cloudflarestorage.com' } })
s3Adapter({ bucket: 'assets', client: new S3Client({ region: 'eu-central-1' }) })
r2Adapter(env.MEDIA)
gcsAdapter(new Storage().bucket('assets'))
azureAdapter(BlobServiceClient.fromConnectionString(connection).getContainerClient('media'))
bunnyAdapter({
apiKey: process.env.BUNNY_STORAGE_API_KEY!,
region: 'ny',
zoneName: process.env.BUNNY_STORAGE_ZONE_NAME!,
})
uploadthingAdapter(new UTApi())
vercelBlobAdapter({ del, list }, { token: process.env.BLOB_READ_WRITE_TOKEN })
localAdapter({ staticDir: 'media' })
The plugin reads the key prefix of an upload collection from the prefix field that the storage plugin adds.
storage. Payload 4 runs the adapters in storage after plugins. When storage is not
empty, janitor moves itself to the end of storage and reads the field there.plugins. They must come before janitor, or startup fails (see
Startup errors). Passing prefix on the collection also fixes this.prefix field. It defaults to '' when the adapter has no prefix or
runs with useCompositePrefixes: true, and the plugin cannot work out the keys from that. For a collection that
reports orphans or missing:
prefix: '';'' for none), plus
compositePrefixes: true. Keys are then prefix/<document folder>/<filename>.A non-empty prefix without compositePrefixes on such a field stops startup, because the keys it gives would look
exact but still be wrong.
janitor({
collections: { media: { prefix: 'media', compositePrefixes: true } },
storage: s3Adapter({ bucket: 'assets', config: { region: 'eu-central-1' } }),
})
{ bucket, config } you pass to s3Storage(). It builds the client from
@aws-sdk/client-s3, an optional peer dependency.
S3Client as client instead. The two commands then still load from
@aws-sdk/client-s3.commands: { DeleteObjectCommand, ListObjectsV2Command } next to
client.NoSuchKey, NotFound or 404 on delete counts as already gone.R2Bucket binding.Bucket.ContainerClient.storage object you pass to bunnyStorage(): apiKey, zoneName and the optional
region, with the same names and region codes. Pass the same object: other fields, such as hostname, are
ignored. It walks directories one request at a time and URL-encodes every path segment.
bunnyData.stream.videoId keeps its video in Stream, not in the zone. So it is never
reported as missing, and it can still be unused. Purging it deletes the document through Payload, and
@seshuk/payload-storage-bunny then deletes the video.{ del, list } from @vercel/blob and an optional token. It stores the blob URL with the
finding and uses it for the delete.staticDir. When each collection has its own directory, pass a function from
collection slug to directory instead. With a function, collections never share a scope.
process.cwd(), as in Payload, so an
absolute path (path.resolve(dirname, 'media')) is the safe choice.prefix
subdirectory) and ignores deeper subdirectories.UTApi. The key is the file name. The adapter stores the uploadthing file key with the
finding as ref and uses it for the delete. See uploadthing for its limits.hasMore.Right before deleting an orphan, the purge looks it up again with list and keys: [key]. Every bundled adapter
except uploadthing does that with one request per key.
uploadthing cannot look up a file by name, so it walks the app's whole file list for every orphan. On a large app, a purge of many orphans makes many requests.
Its listing pages by offset, so a file uploaded or deleted during a scan can shift a page by one. A file that slips
past this way is reported as missing and is never deleted. The next scan sees it again.
uploadthing has no prefixes. The whole app is one flat scope.
- If a collection resolves to a non-empty prefix, the listing throws. Set
prefix: ''.- Several collections on one app see each other's files as one scope. Give them one shared adapter instance. The app is then listed once, and each orphan is reported once (see Shared scope).
- Files with the same name share one key, so a stray copy of a used file's name is never reported. That can only hide an orphan.
A storage scope is one adapter instance plus one prefix. Several listed collections can use the same adapter
instance and the same prefix. The scan then treats them as one scope and uses the union of their keys. An adapter
with perCollection set is the exception.
An orphan in a shared scope belongs to the first collection, in the order of collections, that reports orphans,
so it is written once.
On one adapter, prefixes must be equal or disjoint. Nested or overlapping prefixes stop startup (see Startup errors).
The plugin matches scopes by adapter instance, not by bucket name. It cannot see that two separately created
adapters point at the same bucket. Keys held by any upload collection still count as known, so nothing is
misreported. But each scope lists the bucket again and reports a true orphan once per collection. Pass one instance,
for example through the top-level storage.
An adapter is an object with two functions. The main entry point exports the types.
import type { StorageAdapter } from '@seshuk/payload-plugin-janitor'
type StorageObject = {
/** Full key, prefix included. */
key: string
/** When the object was last written. Without it, `minAge` cannot hold the object back. */
lastModified?: Date
/** Whatever deleting needs and the key does not carry: a URL, a file id. Stored with the finding. */
ref?: string
/** Bytes. Leave it out rather than guess. */
size?: number
}
type StorageScope = {
/** Slug of the upload collection. */
collection: string
/** Key prefix without a trailing slash. An empty string is the root. */
prefix: string
}
type StorageListArgs = StorageScope & {
/** When set, only these keys (all inside `prefix`) are needed. List just them, or ignore the field. */
keys?: string[]
}
type StorageAdapter = {
delete: (args: StorageScope & Pick<StorageObject, 'key' | 'ref'>) => Promise<void>
list: (args: StorageListArgs) => AsyncIterable<StorageObject[]>
/** Dotted path of a field that marks a document whose file this storage never holds, such as a video in a streaming service. */
external?: string
/** The listing depends on `collection`, not only on `prefix`: collections never share a scope. */
perCollection?: boolean
}
Two rules matter:
list must walk the whole prefix or throw. A listing that stops short looks like an empty bucket. Every
document whose file was not reached is then reported as missing.delete must resolve when the object is already gone. If a 404 counts as a failure, the finding waits forever
for a deletion that cannot happen.More about list and delete:
list yields pages, one per provider request, in any order.keys is set, the caller filters the result itself, so an adapter may list the whole prefix instead. Every
key that exists must still come back.access is one function for every action, or an object with one function per action. A missing key gets the
default: a logged-in user of the admin.user collection, or any logged-in user when admin.user is not set.
| Action | Covers |
|---|---|
read | Reading findings and runs, the Cleanup widget and the usage route. |
approve | Changing a finding's status or note, and deleting findings and runs that are not running. |
scan | The scan route. |
purge | The purge route. The user also needs delete access on the collections it deletes from. |
janitor({
collections: { media: true },
access: {
read: ({ req }) => Boolean(req.user),
approve: ({ req }) => req.user?.role === 'editor' || req.user?.role === 'admin',
purge: ({ req }) => req.user?.role === 'admin',
},
})
For a purge, the plugin also runs the delete access of every listed collection that has findings marked delete.
Each must return true for the user. false or a Where query returns 403. startJanitor, runJanitor and
purgeApproved called from your own code skip both checks.
With @payloadcms/plugin-multi-tenant, set tenants to give findings a tenant:
janitor({
collections: { media: true, pages: true },
storage,
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. |
true uses the multi-tenant plugin's defaults. Pass an object when you renamed its tenantsSlug or its tenant field.
Where the tenant comes from:
missing or unused finding takes the tenant of its document at scan time. The finding's Tenant field holds
it.Who sees what:
read access returns true, for example a super admin under userHasAccessToAllTenants. A super admin counts only
when that access returns exactly true. If it returns a query, even one that matches every tenant, the user counts
as a tenant admin and cannot scan or purge.403.access still applies on top. A user needs both access and the tenant check.hasMany. An admin of any one of them can then
read and approve its finding. A purge still checks the tenants again before it deletes.When a document moves to another tenant:
minAge sets its finding back to found and writes the new tenant. A decision made for one
tenant does not carry over to another one.unused finding, the move changes the document, so scans skip it until it is older than minAge again.
During this window, the finding keeps its old tenant and its decision, and admins of the old tenant still see it.delete, the purge skips it and sets
keep with the note "the document moved to another tenant".Findings written before you turned tenants on keep their decisions. The next scan fills in their tenant.
Also keep in mind:
read access, and that access can return true for users who
are not super admins:
useTenantsCollectionAccess: false, the multi-tenant plugin does not limit the tenants collection. Every
user it admits counts as seeing every tenant.access admits such users, they may see every finding
and may scan and purge.tenants adds a table for the findings' tenant relation. Create and run a migration.delete access on the target collection to return true. The multi-tenant plugin returns a query
for tenant admins, so only a super admin can purge.tenant field counts as a use of a tenant only when the tenants collection itself is listed in collections.blockDelete on tenant-scoped collections, the guard also runs when the multi-tenant plugin deletes a
tenant's documents after the tenant itself is deleted. A guard error there can roll back the tenant delete.collections.Usage detection reads the database, not only the config. A document counts as referenced when its id appears in any of these:
_rels tables and polymorphic relationships;json fields, blocks (also with blocksAsJSON and block references from config.blocks)
and rich text;Ids are compared as whole values, never as substrings. When in doubt, the plugin counts a document as used.
Foreign keys come from the database catalog: pg_constraint on Postgres, pragma_foreign_key_list on SQLite. Any
table with a foreign key to the collection counts, your own tables included.
schemaName.relationship or upload field points at the collection but no foreign key to it is visible, usage
detection throws instead of answering "unused".references.text. Off by default. When on, ids stored whole in plain text, varchar and select columns
count too. This is still a whole-value match: a text field holding 12 matches document 12, a field holding
see 12 does not. On MongoDB, text: true walks every collection in full instead of only the candidate fields.
This is slower, but never less safe.
references.versions. With 'used' (the default), a reference from any version keeps a document. With
'unused', references held only by old versions do not, and such a document is reported as unused. The finding's
usage lists the version references, and the findings list shows Only in old versions. The latest version of a
document, the current draft included, always counts as live.
references.ignoreTables. Names whose references do not count, for example an audit log or analytics.
_rels, _locales,
array and block tables and its _v version tables.Usage detection throws a janitor: error whenever it cannot give a sure answer. Examples: a missing foreign key as
above, a transaction whose driver is neither pg nor libsql, a document nested too deep on MongoDB.
The plugin never reads such an error as "unused":
These details matter if you are tracing why a document counts as used.
On Postgres and SQLite, the plugin reads JSON columns only where a reference can be. For each collection and global, it finds the top-level fields that can hold one:
relationship or upload field pointing at the collection;json or richText field;blocks field whose blocks it cannot resolve;It reads a JSON column of that entity only when the column belongs to one of those fields:
dbName are traced back through the adapter's table map.Reading every JSON column would match numeric ids of one collection against unrelated numbers in another. On MongoDB, likewise, a collection Payload did not create is read whole.
The plugin reads table suffixes (versionsSuffix, relationshipsSuffix, localesSuffix) from the database
adapter, so custom suffixes work. A table with a suffix it does not recognize reads as an ordinary table. That only
makes more references count.
A lookup for one document (the delete guard, a purge, the panel) first narrows JSON rows in the database. It uses
strpos for jsonb columns on Postgres and instr on SQLite. Rows whose text might hold the id in another form
pass too:
4.99999999999999999 parses as 5);The narrowing only lets extra rows through. The walk described below decides.
A JSON value that cannot be read, such as SQLite's binary JSONB, fails closed. A lookup counts it as a reference,
and the scan writes no unused findings for that collection.
A reference is found by comparing a value with the id, so a JSON value 12 does count as a reference to document
12. That errs on the side of "used", which is the safe side.
Every key of a plain object is read. Rich-text editor nodes are the exception. A node is an object with a string
type and a numeric version. In a node, plain values under these layout keys are skipped: colSpan, detail,
direction, format, headerState, indent, mode, relationTo, rowSpan, start, style, textFormat,
textStyle, type and version. This way a node's version: 1 never reads as document 1.
A few node types have layout keys of their own. Their plain values, or lists of plain values, are skipped:
listitem.value, list.listType and list.tag, heading.tag, table.colWidths, table.frozenColumnCount,
table.frozenRowCount, tablecell.width and tablerow.height.
An object under one of these keys is still read, and so is every other key. An id inside a custom node counts.
JSON is walked 128 levels deep. Anything deeper fails closed:
unused findings for that collection and logs a warning.With blockDelete (on by default), a delete fails while the document is still referenced. The error gives the total
number of places that use the document and names up to three of them:
This document is still used in 3 places, among them <title › field>, ... Remove it there first.
The guard follows references.versions, like a scan and a purge:
'used' (the default), a reference from any version blocks the delete.'unused', a reference held only by old versions does not. The latest draft still does.The guard runs inside the delete's own transaction. When usage detection throws, the delete fails with that error instead of going through.
purgeApproved bypasses the guard, because it has already checked the document again with the same rule. The bypass
is a context value that names the exact collection and document being purged, so it covers only that delete. REST
and GraphQL requests cannot set it.
Each listed collection gets a Usage panel on the edit view, unless usagePanel is false. The panel asks the
server where the document is used right now. It does not depend on scans or findings.
The panel opens with a verdict. Below it, it lists the documents that reference this one: the fields, the locales and the status (live, draft, version, in trash).
admin on, the field is highlighted when the document opens.The verdict follows from the places the server lists and its used answer:
| Places listed | used | Verdict |
|---|---|---|
| any published one | any | Used on the live site. "N live places break if you delete this document." |
| drafts or trashed documents, no published one | any | Still in use. "Used by N drafts or trashed documents, so it counts as used." |
| only old versions, or none | true or missing | Still in use. "Older versions still refer to it, so it counts as used." |
| only old versions | false | Safe to delete. "Only older versions still hold it." |
| none | false | Safe to delete. "Nothing uses this document." |
The panel says "Safe to delete." only when the server returns used: false. With references.versions: 'used' (the
default), that means no reference at all.
Two states never read as safe:
janitor({
collections: {
media: true,
banners: { usagePanel: { position: { after: 'alt' }, limit: 5 } },
icons: { usagePanel: false },
},
storage,
})
position: 'sidebar', 'first', 'last', { after: 'field' } or { before: 'field' }. Named fields are
found inside rows, groups, collapsibles and tabs. The default is 'sidebar', and 'first' on an upload
collection. Payload 4 shows the sidebar of an upload collection below all its fields, where the panel is easy to
miss.limit: how many documents the panel shows before the rest move behind a "Show all" button. The button opens a
drawer. 0 (the default) shows 3. The drawer always shows all of them, with filters by status.overrides: Payload field overrides for the panel's ui field. name and type stay as they are.The panel calls the usage route, so it needs the endpoints.
Set usagePanel: false on the collection and add the field yourself. The collection must still be listed, because
the usage route serves only listed collections. Pass endpointsPath if you changed endpoints.path.
import { usageField } from '@seshuk/payload-plugin-janitor'
fields: [{ name: 'alt', type: 'text' }, usageField({ limit: 10 })]
In a custom component, use UsagePanel from @seshuk/payload-plugin-janitor/client. It shows the document being
edited, or any other document when you pass collectionSlug and id.
A run is a scan or a purge. Only one runs at a time. The jobs option decides where runs happen. It is false (the default) or an
object with these keys:
| Key | Type | Default | What it does |
|---|---|---|---|
queue | string | 'default' | Payload jobs queue the janitor-run task is added to. Something must run that queue. |
schedule | string | none | Cron for a scheduled scan, for example 0 3 * * *. See Schedule. |
jobs: false (the default). A scan or purge started from the admin UI, the endpoints or startJanitor runs
inside the request. The request waits for the run and gets its result.jobs: {} or jobs: { queue }. Every run, from the admin UI, the endpoints or startJanitor, is queued
as the Payload job janitor-run on queue ('default' when left out). Something has to run that queue:
Payload's jobs.autoRun, a call to payload.jobs.run(), or GET /api/payload-jobs/run?queue=<queue>. If nothing
does, the run never happens.jobs: { schedule }. Also queues a scan on that cron, on the same queue.On serverless platforms, set jobs. An inline run lives only as long as the request. If the request dies, the run
counts as abandoned only after 30 minutes without a heartbeat (see
Heartbeat and abandoned runs).
jobs.schedule gives the janitor-run task a Payload schedule that queues a scan on jobs.queue.
jobs.autoRun or calls to GET /api/payload-jobs/handle-schedules.autoRun never fires on serverless platforms. There, call both endpoints from an external cron (see
the serverless recipe).jobs.access.run decides who may call them.export default buildConfig({
jobs: {
autoRun: [{ cron: '*/5 * * * *', queue: 'janitor' }],
},
plugins: [
janitor({
collections: { media: true },
storage,
jobs: { queue: 'janitor', schedule: '0 3 * * *' },
}),
],
})
Both functions take payload and a mode, 'scan' (the default) or 'purge'; any other mode throws. Both read
the installed options from payload, and both throw janitor: the plugin is not installed on this Payload config
when the plugin is missing or has enabled: false.
startJanitor(payload, mode?) follows jobs, the same way the admin button does. With jobs: false, it runs
inside the call. With jobs set, it queues the run. It returns a StartResult.runJanitor(payload, mode?) always runs inside the current process and ignores jobs. Use it in your own
scheduler or worker. It returns the scan or purge report, or null when another run holds the lock.import { runJanitor } from '@seshuk/payload-plugin-janitor'
const report = await runJanitor(payload, 'purge')
Every run is recorded in Janitor runs with its mode, status (running, done, failed), times, counts and the
error, if any.
reclaimableBytes, the bytes its orphans and unused files hold, for the dashboard widget.deleted, failed (the delete or the storage look-up threw) and skipped (a check kept the
finding), plus freedBytes. A queued purge has no toast, so these counts are where you see its problems.purgedBy.The run edit view opens with a card: what the run did, when it started, how long it took and its counts. Below the card, a table breaks the run down by collection:
The table is built from the findings each time you open the run, so it is never stored. The raw fields are in a collapsed Details group.
running is refused. The endpoint returns 409 and names the blocking run in
blockedBy.lock field
with a unique index. A start that cannot take the lock is refused in the same way.Known limits of the lock:
With jobs set:
running, and then queues the job.runId. A job still waiting in the queue blocks a start like a running run.failed.running when the job starts, for example because it was abandoned, the job starts a new
run instead.A running run records a heartbeat (heartbeatAt) as it works, at most once a minute. It records one:
The plugin judges a run by its last heartbeat, or by startedAt when it has none. Once that time is more than 30
minutes old, the run counts as abandoned. The next start marks it failed with "Abandoned: no sign of life for 30
minutes, so the worker most likely stopped". Then the new run goes ahead.
A queued run gets its heartbeat once, when the start creates it. The heartbeat does not move while the job waits, so a job that waits more than 30 minutes is abandoned the same way.
Each finding is one row in Janitor findings, unique on (collectionSlug, objectKey).
| Field | Label | Holds |
|---|---|---|
objectKey | Key | The storage key, or <slug>/<id> for a document of an ordinary collection. |
kind | Finding | orphan, missing or unused. |
status | Status | found (shown as Undecided), keep, delete (shown as To delete) or deleted. |
collectionSlug | Collection | The collection the finding belongs to, shown by its label. |
documentId | Document | For missing and unused: the document's title with a link, a thumbnail for uploads, or "Document no longer exists". |
tenant | Tenant | With tenants: the tenants of the document at scan time. See Multi-tenant. |
size | Size | Object or file size in bytes, when known, shown in human-readable units. |
uploadedAt | Created at | The object's last-modified time for orphans, the document's creation time for missing and unused. |
lastSeenAt | Last seen at | When a scan last reported it. |
run | Found by | The last scan that reported it. |
purgedBy | Purged by | The purge run that acted on it. |
usage | Usage | For unused, the references that did not count (old versions), shown as "References at scan time". |
onlyVersions | Only in old versions | Computed, not stored, shown for unused: every remaining reference is in an old version. |
purgedAt | Deleted at | When the purge deleted it. |
note | Note | Free text. The purge writes why it kept or skipped a finding. |
error | Error | The error from the last purge whose delete or storage look-up threw. See Purge results. |
ref | hidden | What the adapter's delete needs besides the key, such as a blob URL or a file id. |
An orphan whose ref is an http(s) URL shows a link to the file in the Document column. A finding with a
document also shows the live usage panel above its stored usage.
found.delete or keep.delete findings. It sets deleted, or keep with a note when the second check fails.Who can change what:
deleted (a purge) or moves a finding away from it (a scan thatpayload plugin backup postgres
Scheduled and on-demand PostgreSQL backups with selective restore, stored in Vercel Blob or S3-compatible storage
72118/wk3v3
cloud storage
Store Payload uploads in third-party cloud storage through a generic adapter interface
1001.0M/wk46.1kv3 v4
payload plugin backup mongodb
MongoDB backup and restore for Payload with Vercel Blob or S3-compatible storage and an admin dashboard
5484/wk8v3
payload plugin switch env
Switch between production and development databases or copy production data to development from the Payload admin
5384/wk5v3
payload db check
Admin view that finds duplicates, broken references and one-sided links, with opt-in previewed repairs
399/wk0v3
payload upstash
Upstash Redis key-value adapter for Payload's built-in KV store
82333/wk7v3 v4