maximseshuk

payload plugin janitor

by maximseshuk
Databases & data
v4
>=4.0.0-beta.4 <4.0.0-canary.0 || ^4.0.0
>=4.0.0-beta.4 <4.0.0-canary.0 || ^4.0.0 · prerelease
MIT

Overview

Summary generated from the README

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.

Features

  • Reports orphaned files, missing files and unused documents as reviewable findings
  • Detects references across relationships, JSON, blocks, rich text, globals and versions
  • Re-checks every approved finding right before purging
  • Usage panel and delete guard block removing documents that are still referenced
  • Runs in the request, as a Payload job, on a cron or from code
  • Separate access rules for reading, approving, scanning and purging

Use cases

  • Reclaim bucket space by removing uploads that no document uses
  • Audit a media library for documents whose files are missing from storage
  • Clean up unused tags or categories in ordinary collections safely

From the author

Housekeeping for Payload: find orphaned files, broken uploads and documents nothing references, then delete only what you approve.

Installation

npm i @seshuk/payload-plugin-janitor

7

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

GitHub stars

7+7 since Oct 11

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 20267
Dec 5, 20267
Dec 4, 20267
Dec 3, 20267
Dec 2, 20267
Dec 1, 20267
Nov 30, 20267
Nov 29, 20267
Nov 28, 20267
Nov 27, 20267
Nov 26, 20267
Nov 25, 20267
Nov 24, 20267
Nov 23, 20267
Nov 22, 20267
Nov 21, 20267
Nov 20, 20267
Nov 19, 20267
Nov 18, 20267
Nov 17, 20267
Nov 16, 20267
Nov 15, 20267
Nov 14, 20267
Nov 13, 20267
Nov 12, 20267
Nov 11, 20267
Nov 10, 20267
Nov 9, 20267
Nov 8, 20267
Nov 7, 20266
Nov 6, 20266
Nov 5, 20266
Nov 4, 20266
Nov 3, 20265
Nov 2, 20265
Nov 1, 20265
Oct 31, 20265
Oct 30, 20265
Oct 29, 20265
Oct 28, 20265
Oct 27, 20265
Oct 26, 20265
Oct 25, 20265
Oct 24, 20265
Oct 23, 20265
Oct 22, 20265
Oct 21, 20265
Oct 20, 20265
Oct 19, 20265
Oct 18, 20265
Oct 17, 20263
Oct 16, 20263
Oct 15, 20262
Oct 14, 20260
Oct 13, 20260
Oct 12, 20260
Oct 11, 20260
npm weekly downloads

11−43 since Oct 18

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 202611
Dec 5, 202613
Dec 4, 202614
Dec 3, 202618
Dec 2, 202617
Dec 1, 202620
Nov 30, 202622
Nov 29, 202618
Nov 28, 202615
Nov 27, 202614
Nov 26, 202611
Nov 25, 20267
Nov 24, 20266
Nov 23, 20264
Nov 22, 202610
Nov 21, 202611
Nov 20, 202617
Nov 19, 202618
Nov 18, 202626
Nov 17, 202624
Nov 16, 202625
Nov 15, 202623
Nov 14, 202622
Nov 13, 202618
Nov 12, 202618
Nov 11, 202611
Nov 10, 202617
Nov 9, 202628
Nov 8, 202628
Nov 7, 202632
Nov 6, 202632
Nov 5, 202637
Nov 4, 202636
Nov 3, 202638
Nov 2, 202636
Nov 1, 202647
Oct 31, 2026178
Oct 30, 2026185
Oct 29, 2026178
Oct 28, 2026177
Oct 27, 2026174
Oct 26, 2026178
Oct 25, 2026175
Oct 24, 202694
Oct 23, 202685
Oct 22, 202685
Oct 21, 202685
Oct 20, 202680
Oct 19, 202666
Oct 18, 202654

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

Health Score

56/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/1419092898-root.svg)](https://payloaddirectory.dev/plugins/1419092898-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1419092898-root"><img src="https://payloaddirectory.dev/badge/1419092898-root.svg" alt="Payload Directory"></a>
Updated Dec 2, 2026Created Oct 14, 2026Published Oct 14, 2026

README

Janitor Plugin for Payload

Janitor Plugin for Payload

Housekeeping for Payload: find orphaned files, missing files and unused documents by comparing your storage with your database.

GitHub release npm version npm downloads CI license Ko-fi

Contents

Features

  • Three kinds of findings. Orphaned and missing files, plus documents nothing references, in upload or ordinary collections.
  • References from the database. Foreign keys, _rels, JSON, blocks, rich text, globals and versions. Unsure means used.
  • You decide. A scan only writes findings. Only what you mark is deleted, after a second check.
  • Usage panel and delete guard. See where a document is used, and block deleting it while it is still used.
  • Any storage. S3 and S3-compatible, R2, Google Cloud Storage, Azure, Bunny, uploadthing, Vercel Blob or local disk. No extra dependencies.
  • Runs your way. In the request, as a Payload job, on a cron or from your own code.
  • Admin menu and widget. Scan and purge from the findings list, in every language Payload ships.
  • Access per action. Separate rules for reading, approving, scanning and purging.

Screenshots

The dashboard widget shows what the last scan found and how much space you can free:

The Janitor widget on the dashboard

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

The findings list with the Janitor menu open

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

An unused file finding with its status choice

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

The usage panel on a media document

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

A finished scan run with its breakdown by collection

Getting started

Versions

PluginPayloadNode.jsInstall
1.x424.22.1+@seshuk/payload-plugin-janitor@beta
0.x322+@seshuk/payload-plugin-janitor@0
  • 1.x is in beta under the beta npm tag. Payload 4 is published under beta too.
  • 1.x needs Payload 4.0.0-beta.4 or later and Next.js 16.4 or later. Canary builds are not supported.
  • 0.x needs Payload 3.83 or later.
  • Usage detection needs the Postgres, SQLite or MongoDB database adapter.

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.

Quick start

Install
# Payload 4
pnpm add @seshuk/payload-plugin-janitor@beta

# Payload 3
pnpm add @seshuk/payload-plugin-janitor@0
Configure
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.

Next steps
  1. Run payload generate:importmap, so the admin panel can find the plugin's menu, panel and widget.
  2. Open Janitor findings and choose Run a scan from the list menu.
  3. Choose Show undecided findings. Mark each finding To delete or Keep, one by one or several at once with Mark selected as "To delete".
  4. Choose Delete approved. The purge checks every finding again and deletes only what passes.

Nothing is deleted before step 4.

How it works

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.

KindWhat it meansExampleCan be purged?
orphanA 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.
missingA 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.
unusedA 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:

  1. Scan. A scan goes through every listed collection and writes what it finds to Janitor findings. It never deletes anything. Anything younger than minAge (24 hours by default) is left out.
  2. Review. A new finding is Undecided (found). You mark it To delete (delete) or Keep (keep).
  3. Purge. A purge takes every finding marked delete and checks it again right before it acts. See What a purge checks.
  4. Delete. The purge deletes only what passes the check, and sets the finding to deleted. A finding that fails the check goes to keep, with a note that says why.
  5. Rescan. The next scan updates the facts but keeps your decisions. It removes undecided findings it no longer sees. See Rescans.
What a scan checks
  • orphans lists the collection's storage under its prefix. It reports every object whose full key no document holds.
    • Known keys come from every upload collection in the config, listed or not. They include the original kept beside a converted file (original.filename), image variants (variants.*.filename), trashed documents and draft versions.
    • For a collection that is not listed, or whose prefix is unknown, keys are matched by their tail: 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.
    • A draft that was never published keeps its first file name on the document, even after a later draft replaced the file. Such a draft is checked against the file of its latest version instead.
  • unused builds a reverse index of references to the collection's documents. It reports every document with none.
    • Trashed documents are skipped.
    • An upload whose file is already missing is reported as missing only, not also as unused.
    • Sometimes the index cannot be read completely, for example when JSON is nested too deep. The scan then writes no 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.
    • If usage detection throws, the run fails.

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.

What a purge checks

Orphans. An orphan is deleted only if all of these are true:

  • Its key is inside the collection's prefix.
  • No document holds the key now, trashed documents and versions included.
  • The object is still there and older than 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:

  • It still exists and is the same document the scan saw: its createdAt equals the finding's uploadedAt (shown as Created at). An id that a newer document reused is never deleted.
  • With tenants, it still belongs to the tenants the finding names. See Multi-tenant.
  • It is not in the trash.
  • Its updatedAt is older than minAge.
  • Nothing references it now.
  • No other document holds the same file.

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.

Configuration

Options

OptionTypeDefaultWhat it does
enabledbooleantruefalse switches the plugin off but keeps its schema. See below.
collectionsRecord<slug, boolean | object>requiredThe collections to scan and guard, by slug. false skips an entry. See Per collection.
storageStorageAdapternoneListing and deletion for every upload collection without its own storage. See Storage adapters.
minAgenumber86400 (24 hours)Seconds. Anything younger is never reported or deleted. See below.
jobsfalse | JobsOptionsfalseRun scans and purges inside the request, or queue them as Payload jobs. See Starting runs.
accessJanitorAccessOptionssee AccessWho may read, approve, scan and purge. See Access.
tenantsboolean | { collection?, field? }falseFindings per tenant, for @payloadcms/plugin-multi-tenant. See Multi-tenant.
references.ignoreTablesstring[][]Tables or collections whose references do not keep a document. See Reference options.
references.textbooleanfalseAlso 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.
adminfalse | { group?, widget? }{ group: 'System', widget: true }Findings list menu, nav group and dashboard widget. See Admin UI.
endpointsfalse | { path? }{ path: '/janitor' }REST routes for scan, purge and the usage panel. See REST endpoints.
overrides{ findings?, runs? }noneChanges to the plugin's two collections. See Overrides.
telemetryboolean | { url? }trueAnonymous 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 })
Per collection

collections.<slug> takes true, false or an object:

OptionTypeDefaultWhat it does
reportboolean | Check[]trueWhich checks a scan runs. false scans nothing but keeps the panel and the guard. See below.
usagePanelboolean | UsagePanelOptionstrue (false with endpoints: false)The "where is this used" panel on the edit view. See Usage panel.
blockDeletebooleantrueRefuse a delete while something still references the document. See Delete guard.
storageStorageAdapterthe top-level storageListing and deletion for this collection's files. Upload collections only.
prefixstringthe 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.
compositePrefixesbooleanfalseThe 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:

Collectionreport: 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

overrides.findings and overrides.runs take Payload collection settings:

  • Top-level keys replace the default.
  • 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.

Storage adapters

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.

StorageAdapterImport
@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 bindingr2Adapter@seshuk/payload-plugin-janitor/r2
@payloadcms/storage-gcsgcsAdapter@seshuk/payload-plugin-janitor/gcs
@payloadcms/storage-azureazureAdapter@seshuk/payload-plugin-janitor/azure
@seshuk/payload-storage-bunnybunnyAdapter@seshuk/payload-plugin-janitor/bunny
@payloadcms/storage-uploadthinguploadthingAdapter@seshuk/payload-plugin-janitor/uploadthing
@payloadcms/storage-vercel-blobvercelBlobAdapter@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' })
Plugin order and prefix

The plugin reads the key prefix of an upload collection from the prefix field that the storage plugin adds.

  • Storage plugins in 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.
  • Storage plugins in plugins. They must come before janitor, or startup fails (see Startup errors). Passing prefix on the collection also fixes this.
  • Empty default. Payload 4 always adds the 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:
    • stored without a prefix, pass prefix: '';
    • with composite prefixes, pass the same prefix you gave the adapter ('' 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' } }),
})
Adapter details
  • s3: takes the same { bucket, config } you pass to s3Storage(). It builds the client from @aws-sdk/client-s3, an optional peer dependency.
    • You can pass an existing S3Client as client instead. The two commands then still load from @aws-sdk/client-s3.
    • To skip the SDK import entirely, pass commands: { DeleteObjectCommand, ListObjectsV2Command } next to client.
    • A NoSuchKey, NotFound or 404 on delete counts as already gone.
  • r2: takes the R2Bucket binding.
  • gcs: takes a Bucket.
  • azure: takes a ContainerClient.
  • bunny: takes the same 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.
    • It lists the storage zone only. A Bunny Stream video is never listed or deleted by the adapter.
    • A document with 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.
  • vercelBlob: takes { del, list } from @vercel/blob and an optional token. It stores the blob URL with the finding and uses it for the delete.
  • local: takes the collection's 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.
    • Pass the same value the collection uses. A relative path resolves against process.cwd(), as in Payload, so an absolute path (path.resolve(dirname, 'media')) is the safe choice.
    • Payload writes local files flat, so the adapter lists only files directly in that directory (or in its prefix subdirectory) and ignores deeper subdirectories.
    • It refuses a key that would leave the directory.
    • It reads the whole directory in one page.
  • uploadthing: takes a 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.
Listing and lookups
  • A listing throws when the provider marks it as truncated but returns no continuation token or cursor (s3, r2, vercelBlob).
  • An uploadthing page that is empty while more files are reported also throws.
  • Vercel Blob and uploadthing page by 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

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.
Shared scope

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.

Writing an adapter

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.
  • When 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.
  • Both functions take a single object, so later releases can add fields without breaking existing adapters.

Access

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.

ActionCovers
readReading findings and runs, the Cleanup widget and the usage route.
approveChanging a finding's status or note, and deleting findings and runs that are not running.
scanThe scan route.
purgeThe 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.

Multi-tenant

With @payloadcms/plugin-multi-tenant, set tenants to give findings a tenant:

janitor({
  collections: { media: true, pages: true },
  storage,
  tenants: true,
})
KeyTypeDefaultWhat it does
collectionstring'tenants'Slug of the tenants collection.
fieldstring'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:

  • A missing or unused finding takes the tenant of its document at scan time. The finding's Tenant field holds it.
  • An orphan has no document, so it has no tenant.
  • A listed collection without the tenant field gives its findings no tenant. Startup logs each such collection.

Who sees what:

  • A user who sees every tenant reads and decides every finding. Such a user is one for whom the tenants collection's 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.
  • Any other user reads, approves and deletes only the findings of the tenants they may read. They never see findings without a tenant.
  • Runs, the Cleanup widget, scans and purges are only for users who see every tenant. For anyone else, the scan and purge routes return 403.
  • access still applies on top. A user needs both access and the tenant check.
  • A document can belong to several tenants when the tenant field has 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:

  • The first scan after 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.
  • For an 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.
  • A purge checks the tenant again. If the document moved after you marked 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:

  • The tenant check trusts the tenants collection's read access, and that access can return true for users who are not super admins:
    • With useTenantsCollectionAccess: false, the multi-tenant plugin does not limit the tenants collection. Every user it admits counts as seeing every tenant.
    • The multi-tenant plugin limits only users of its admin users collection. A user of another auth collection gets the plain access of the tenants collection. If your janitor access admits such users, they may see every finding and may scan and purge.
  • On Postgres and SQLite, tenants adds a table for the findings' tenant relation. Create and run a migration.
  • A purge needs 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.
  • The tenant field counts as a use of a tenant only when the tenants collection itself is listed in collections.
  • With 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.
  • Do not list the plugin's findings and runs collections in the multi-tenant plugin's collections.

Usage detection

References

Usage detection reads the database, not only the config. A document counts as referenced when its id appears in any of these:

  • foreign keys, including Payload's _rels tables and polymorphic relationships;
  • ids stored inside JSON: json fields, blocks (also with blocksAsJSON and block references from config.blocks) and rich text;
  • on MongoDB, any value inside the fields that can hold a reference;
  • globals;
  • versions and drafts.

Ids are compared as whole values, never as substrings. When in doubt, the plugin counts a document as used.

Foreign keys

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.

  • On Postgres, a database role that owns no table still sees them.
  • The plugin looks up the tables in the adapter's schemaName.
  • When a relationship or upload field points at the collection but no foreign key to it is visible, usage detection throws instead of answering "unused".
Reference options

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.

  • On Postgres and SQLite, a collection or global slug covers all of that entity's tables: its _rels, _locales, array and block tables and its _v version tables.
  • On MongoDB, a collection slug covers its collection and its versions collection.
  • Any other name must match a table (Postgres, SQLite) or a MongoDB collection exactly.
  • The plugin always ignores Payload's locked-documents, migrations, key-value, preferences and jobs tables, and its own findings and runs collections.
When usage detection throws

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":

  • A scan fails.
  • A purge stops.
  • The delete guard refuses the delete.
  • The panel shows an error.
How references are read

These details matter if you are tracing why a document counts as used.

JSON columns

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:

  • a relationship or upload field pointing at the collection;
  • a json or richText field;
  • a blocks field whose blocks it cannot resolve;
  • a group, array or named tab with such a field inside.

It reads a JSON column of that entity only when the column belongs to one of those fields:

  • Column names are matched by the field name in snake_case.
  • Tables renamed with dbName are traced back through the adapter's table map.
  • Array and block tables of such an entity are read whole.
  • A column no field produces, such as one you added by hand, is always read. So is a table Payload did not create, such as one of your own.

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.

Lookups for one document

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:

  • a long run of digits next to a decimal point (4.99999999999999999 parses as 5);
  • on SQLite, a backslash escape, an exponent, or a binary JSONB value.

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.

How ids are matched

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:

  • A lookup for one document (the delete guard, a purge, the panel) counts it as a reference.
  • The scan writes no unused findings for that collection and logs a warning.
  • On MongoDB, a document nested that deep makes usage detection throw.

Delete guard

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 count covers every place that blocks the delete, including ones the user cannot read.
  • The names cover only places the deleting user may read. Their titles are read under that user's own access. When the user may read none of the places, the message names their collections instead.
  • Without a user, a delete through the Local API uses the system's access, so every place can be named. A REST or GraphQL delete without a user names only the places anyone may read.
  • A place without a title is named by its collection or global label, in the language of the request, and its id.
  • When the places cannot be listed, the message names the collections, or the tables no collection owns.

The guard follows references.versions, like a scan and a purge:

  • With 'used' (the default), a reference from any version blocks the delete.
  • With '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.

Usage panel

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).

  • References that exist only in older versions are grouped under a link that opens those versions. This link works in the panel itself and in the "Show all" drawer.
  • Each entry links to the document. With admin on, the field is highlighted when the document opens.
  • A reference from a table no collection owns is listed by table name, without a link.
  • The panel lists only places the viewer may read, and reads their titles with the viewer's own access.
  • Field labels come in the viewer's language. A reference inside a localized field lists its locale.
Verdict

The verdict follows from the places the server lists and its used answer:

Places listedusedVerdict
any published oneanyUsed on the live site. "N live places break if you delete this document."
drafts or trashed documents, no published oneanyStill in use. "Used by N drafts or trashed documents, so it counts as used."
only old versions, or nonetrue or missingStill in use. "Older versions still refer to it, so it counts as used."
only old versionsfalseSafe to delete. "Only older versions still hold it."
nonefalseSafe 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:

  • A failed request shows "Could not load usage" with a retry button.
  • An unsupported database shows "Usage cannot be checked on this database".
Panel options
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.

Placing the panel by hand

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.

Running and reviewing

Starting runs

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:

KeyTypeDefaultWhat it does
queuestring'default'Payload jobs queue the janitor-run task is added to. Something must run that queue.
schedulestringnoneCron 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).

Schedule

jobs.schedule gives the janitor-run task a Payload schedule that queues a scan on jobs.queue.

  • Queuing on schedule needs Payload's jobs.autoRun or calls to GET /api/payload-jobs/handle-schedules.
  • Running the queued scan needs the same as any queued run, see above.
  • autoRun never fires on serverless platforms. There, call both endpoints from an external cron (see the serverless recipe).
  • Payload's 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 * * *' },
    }),
  ],
})
From your own code

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')
Run records

Every run is recorded in Janitor runs with its mode, status (running, done, failed), times, counts and the error, if any.

  • A scan also stores reclaimableBytes, the bytes its orphans and unused files hold, for the dashboard widget.
  • A purge stores 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.
  • A scan run lists the findings no later run has taken over. A purge run lists the findings that still name it in purgedBy.
  • A count that does not apply to the mode is hidden on the run and empty in the list. A count that is not known yet stays empty.

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:

  • For a scan, it counts the findings that still name this run, by kind.
  • For a purge, it counts the findings that still name this purge: the ones it deleted and the ones it did not delete. The Janitor findings list below the card shows each of them with its note and, for a failed delete, its error.

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.

Run lock
  • A second start while a run is running is refused. The endpoint returns 409 and names the blocking run in blockedBy.
  • Two starts at the same moment never both run. A running run holds a lock in the database: a hidden lock field with a unique index. A start that cannot take the lock is refused in the same way.
  • A run gives the lock back when it finishes, fails or is abandoned.
  • On MongoDB, the plugin creates this index itself at startup, even when Payload's own index creation is off.

Known limits of the lock:

  • On SQL databases and on a standalone MongoDB server, a queued job that is delivered twice at the very same moment can perform its run twice.
  • On MongoDB, startup fails when the unique index cannot be built. Some MongoDB-compatible services, such as Cosmos DB, build a unique index only on an empty collection.
Queued runs

With jobs set:

  • The start creates the run at once, with status running, and then queues the job.
  • The response has the runId. A job still waiting in the queue blocks a start like a running run.
  • The job then performs that same run.
  • If queueing the job throws, the run is marked failed.
  • If the run is no longer running when the job starts, for example because it was abandoned, the job starts a new run instead.
Heartbeat and abandoned runs

A running run records a heartbeat (heartbeatAt) as it works, at most once a minute. It records one:

  • per page of the storage listing, of documents and of versions;
  • while the reverse index is built;
  • per finding a purge acts on.

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.

Findings

Each finding is one row in Janitor findings, unique on (collectionSlug, objectKey).

FieldLabelHolds
objectKeyKeyThe storage key, or <slug>/<id> for a document of an ordinary collection.
kindFindingorphan, missing or unused.
statusStatusfound (shown as Undecided), keep, delete (shown as To delete) or deleted.
collectionSlugCollectionThe collection the finding belongs to, shown by its label.
documentIdDocumentFor missing and unused: the document's title with a link, a thumbnail for uploads, or "Document no longer exists".
tenantTenantWith tenants: the tenants of the document at scan time. See Multi-tenant.
sizeSizeObject or file size in bytes, when known, shown in human-readable units.
uploadedAtCreated atThe object's last-modified time for orphans, the document's creation time for missing and unused.
lastSeenAtLast seen atWhen a scan last reported it.
runFound byThe last scan that reported it.
purgedByPurged byThe purge run that acted on it.
usageUsageFor unused, the references that did not count (old versions), shown as "References at scan time".
onlyVersionsOnly in old versionsComputed, not stored, shown for unused: every remaining reference is in an old version.
purgedAtDeleted atWhen the purge deleted it.
noteNoteFree text. The purge writes why it kept or skipped a finding.
errorErrorThe error from the last purge whose delete or storage look-up threw. See Purge results.
refhiddenWhat 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.

Status flow
  1. A scan creates the finding as found.
  2. An admin sets it to delete or keep.
  3. A purge takes delete findings. It sets deleted, or keep with a note when the second check fails.

Who can change what:

  • Only the plugin sets deleted (a purge) or moves a finding away from it (a scan that
README truncated — read the full version on GitHub

Similar plugins