fourdigit

payload plugin search replace

by fourdigit
Admin customization
v3
^3.86.0
MIT

Overview

Summary generated from the README

Adds an admin view where editors search for text across configured collections and replace it after reviewing a preview of every match. It builds on a fork of the official search plugin, using its search collection as an index. Replacements run as the signed-in user with access control applied, and on draft-enabled collections they are saved as new drafts. Requires Payload 3.86 or later and Next.js 15.2.9 or later.

Features

  • Searches text, textarea, hasMany text and Lexical rich text fields, including nested groups, tabs, arrays and blocks
  • Preview of each match with context, letting you pick which ones to apply
  • Replaces inside Lexical text nodes so bold, links and other formatting are kept
  • Plain text, regular expression (RE2, opt-in per user) and full-width/half-width insensitive matching
  • Saves replacements as new drafts and runs all reads and writes with the user's access rights
  • REST endpoints for capabilities, preview and apply, plus English and Japanese admin UI

Use cases

  • Rename a product or brand across all pages and posts, keeping rich text formatting
  • Fix a recurring typo or outdated phrase site-wide after reviewing every match
  • Normalize full-width and half-width characters in Japanese content

From the author

Find and replace text across Payload CMS collections, including Lexical rich text. Forked from @payloadcms/plugin-search.

Installation

npm i @fourdigit/payload-plugin-search-replace

0

Stars

0

Forks

1

Open Issues

1 months ago

Last Updated

0

Weekly Downloads

v

npm Version

Dependencies

GitHub stars

00 since Oct 18

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

Trends appear after 7 days of data. Daily snapshots have not started yet.

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

Health Score

20/100Poor

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

README

Payload Search & Replace Plugin

Find and replace text across Payload CMS collections — plain text, textareas and Lexical rich text — with a preview of every change before anything is saved.

A fork of @payloadcms/plugin-search: its search collection becomes an index of every document's text, used to find candidates quickly. See FORK.md.

Features

  • Search across collections in text, textarea, hasMany text and Lexical richText fields, including fields inside groups, tabs, arrays and blocks
  • Preview every match with its context and the replacement, then pick the ones to apply
  • Saves drafts: on collections with drafts enabled, replacements are saved as a new draft and the published version stays as it is until the draft is published through your normal workflow
  • Keeps rich text formatting: text is replaced inside each Lexical text node, so bold, links and other formats stay. A match that spans formatting boundaries is shown but left for you to fix by hand
  • Matching modes: plain text (optionally case-sensitive), regular expressions (RE2 syntax, opt-in per user), and width-insensitive matching (NFKC) so ABC matches ABC and ガ matches ガ — only the matched range is replaced
  • Respects access control: every read and write runs with overrideAccess: false as the signed-in user, so collection, document and field access (tenants, departments, roles…) apply
  • One locale at a time, without locale fallback
  • Admin view at /admin/search-replace, with a nav link. English and Japanese

Requirements

  • Payload ^3.86.0, Next.js >=15.2.9, React 19
  • @payloadcms/ui, @payloadcms/next and @payloadcms/translations as direct dependencies, at the same version as payload
  • Any Payload database adapter (tested with SQLite; written for PostgreSQL and MongoDB)

Installation

pnpm add @fourdigit/payload-plugin-search-replace
// payload.config.ts
import { searchReplacePlugin } from '@fourdigit/payload-plugin-search-replace'

export default buildConfig({
  // ...
  plugins: [
    searchReplacePlugin({
      collections: ['pages', 'posts'],
      replace: {
        canUseRegex: ({ req }) => Boolean(req.user?.roles?.includes('admin')),
      },
    }),
  ],
})

Then regenerate the import map and, for existing content, build the index once:

pnpm payload generate:importmap

The index is filled when documents are saved. For documents that existed before the plugin was installed, run a reindex (see Access to the index).

Usage

Open Search & Replace from the admin nav, or go to /admin/search-replace.

1. Enter what to find

The search form

  • Find: the text to look for. Replace with: the new text; leave it empty to delete the matches.
  • Mode: plain text or a regular expression (only for users allowed by replace.canUseRegex).
  • Match case, and Ignore full-width / half-width (see step 5).
  • Locale: which locale's text to search and change. Other locales are left as they are.
  • Collections: limit the search to some of the configured collections.

Press Search. Nothing is saved yet.

2. Check the preview

Preview of every match

Each document is listed with every match, the field it is in (its label, plus the path for fields inside groups and arrays), and the text before and after the change. Untick a match, or a whole document, to leave it out. Edit opens the document.

A match that crosses formatting or a link in rich text (here, さくら + ポイント in bold) is shown but can't be ticked: replacing it would lose the formatting, so it says fix by hand.

3. Replace

Confirmation

Replace selected asks for confirmation, then saves each document as the signed-in user, with that user's access rights.

Result

The message counts what happened to each document: updated, unchanged, changed since the search (another edit came first; nothing was written, so search again), or failed. The search then runs again, so what's left is what still matches, like the match to fix by hand.

4. Publish the drafts

Version history after a replace

On collections with drafts, the replacement is a new draft and the published version stays as it is. Review it in the document's Versions tab and publish it through your usual workflow. The version history is also the record of what was replaced and by whom.

5. Full-width and half-width text

Width-insensitive matching

With Ignore full-width / half-width, ABCD also finds ABCD, and ガ finds ガ. Only the matched characters are replaced; the text around them keeps its width.

The screenshots come from the dev app (dev/) and can be regenerated with node dev/screenshots.mjs (see the comment at the top of the file).

Options

All options of @payloadcms/plugin-search are accepted. Defaults that differ from upstream are marked.

OptionTypeDefault
collectionsstring[]—Collections to index and search
fields.excludestring[]DEFAULT_EXCLUDE (below)Glob patterns on the field path (names only, no array indices, e.g. layout.content). * matches one segment, ** any number. Replaces the defaults; spread DEFAULT_EXCLUDE to keep them
fields.include({ collection, field, schemaPath }) => boolean | undefined—Decide per field; true also brings back a hidden field. undefined falls back to the rules below
replace.access({ req }) => boolean | Promise<boolean>users who can open the admin panelWho can open the view and call the endpoints. Document access still applies
replace.canUseRegex({ req }) => boolean | Promise<boolean>nobodyWho can search with regular expressions
replace.maxApplyDocsnumberno limitMost documents one apply request may change
replace.disableAdminViewbooleanfalseLeave out the admin view and nav link; the endpoints stay
syncDraftsbooleantrue (upstream false)The index has to hold draft text, since replacements work on drafts
deleteDraftsbooleanfalse (upstream true)

Fields left out by default

  • Fields hidden from the admin panel (hidden, admin.hidden or admin.disabled, or inside such a field): editors can't see what a replacement would do to them. This covers Payload's upload fields (filename, mimeType, sizes…) and storage plugins' prefix.
  • DEFAULT_EXCLUDE:
    • **.slug, **.url
    • breadcrumbs.** — added by @payloadcms/plugin-nested-docs and rebuilt from the parent pages on every save
    • stripeID — added by @payloadcms/plugin-stripe; the id of the synced Stripe object

To add your own patterns and keep these:

import { DEFAULT_EXCLUDE, searchReplacePlugin } from '@fourdigit/payload-plugin-search-replace'

searchReplacePlugin({
  collections: ['pages'],
  fields: { exclude: [...DEFAULT_EXCLUDE, 'legacyId', 'internal.**'] },
})

Access to the index

The search collection lists text from every indexed document, drafts included, across tenants and departments. So by default nobody can read, update or delete it through the API (upstream allows public reads), and its content / contentRaw fields are never readable, even if you open the collection up. Syncing and search & replace use the Local API and do not need API access.

To see the collection in the admin panel and use upstream's Reindex button, give your administrators access:

searchReplacePlugin({
  collections: ['pages', 'posts'],
  searchOverrides: {
    access: {
      read: isAdmin,
      update: isAdmin,
      delete: isAdmin,
    },
  },
})

Only give reindex to users who can read every indexed document: a reindex rebuilds the index with the documents the user can read.

REST endpoints

The admin view uses these; you can call them yourself.

EndpointBodyReturns
GET /api/search-replace/capabilities—{ canUseRegex, collections, maxApplyDocs }
POST /api/search-replace/preview{ find, replace?, mode?: 'text' | 'regex', caseSensitive?, normalizeWidth?, locale?, collections? }{ documents: [{ collection, id, title, updatedAt, matches: [{ id, fieldLabel?, fieldPath, before, text, after, replacement, replaceable, reason? }] }], totals }
POST /api/search-replace/applythe preview query plus documents: [{ collection, id, matchIds, updatedAt? }]{ results: [{ collection, id, status, appliedIds, skippedIds, message? }] }

status is updated, unchanged, stale (the document changed after the preview; nothing was written) or error. Match ids that were not replaced — changed since the preview, needing a manual fix, or kept by field-level update access — are listed in skippedIds.

Limitations

  • Regular expressions use RE2 syntax (re2js): they run in linear time, so no pattern can stall the server, but backreferences (\1) and lookaround ((?=…), (?<=…)) are not supported. Replacements support $1, $<name>, $& and $$.
  • Fields inside Lexical blocks (BlocksFeature nodes) are not searched.
  • The preview returns every match at once. Very common search terms across large collections make large responses.
  • Searches containing \, and all regular expressions, read every document of the selected collections instead of narrowing with the index.
  • A match that covers only part of a character NFKC expands (e.g. 平 in ㍻) is shown but has to be fixed by hand.
  • After saving, the plugin compares the saved value with the planned one. If your hooks reformat a field on save (trimming, adding data to rich text nodes), the match is reported as not replaced even though the change was saved.
  • When the host uses localization, saving a document re-indexes it in every locale, because non-localized fields are indexed too.

Development

pnpm install
pnpm dev            # dev app on http://localhost:3000 ([email protected] / test)
pnpm test:int       # unit and integration tests (in-memory SQLite)
pnpm lint
pnpm typecheck
pnpm build && pnpm check:pack   # packs the package and checks what would be published

DATABASE_URL in dev/.env picks the adapter: postgres://…, mongodb://…, or unset for SQLite. CI (.github/workflows/ci.yml) runs lint, types, the tests on SQLite and PostgreSQL 16, and the pack check on every pull request.

License

MIT. Includes code from @payloadcms/plugin-search, © Payload CMS, Inc. See LICENSE.md.

Similar plugins