@foundrykit/search-plugin
v0.5.2
Published
A plugin for Payload CMS that provides a cached, grouped and ranked site search over the plugin-search index, with fuzzy matching, editor-controlled relevance and search analytics.
Maintainers
Readme
@foundrykit/search-plugin
Cached, grouped and ranked site search for Payload CMS, layered on top of
@payloadcms/plugin-search.
That plugin keeps a search collection in sync with your content through afterChange /
afterDelete hooks. Sync is the part of an index implementation that rots, so this plugin does not
reimplement it — it owns the read side:
- One index read per request, cached in memory, instead of one query per collection per keystroke
- Fuzzy matching via Fuse.js, so typos, plurals and word order stop mattering
- Ranking by field weight and collection weight, so a title hit beats an incidental description hit
- Grouping with per-group caps, and an opt-in empty-query preset
- Editor operability — reindex on demand, and a "what is searchable" report that gives reasons
- Search analytics — top queries and, more usefully, the ones returning nothing
Why the read side is the interesting half
A naive site search queries each source collection live with a like substring where clause.
That caps how good relevance can ever get: substring matching has no word boundaries (searching
tuni matches anything containing those four letters anywhere), there is no ranking, and there is
nothing to measure or rebuild. Every complaint arrives anecdotally and costs a developer a code
read to diagnose.
Install
pnpm add @foundrykit/search-plugin @payloadcms/plugin-searchUsage
Install it after searchPlugin, since it reads the collection that one creates.
import { searchPlugin as payloadSearchPlugin } from '@payloadcms/plugin-search';
import { searchPlugin } from '@foundrykit/search-plugin';
export default buildConfig({
plugins: [
payloadSearchPlugin({
collections: ['pages', 'posts', 'hotels'],
}),
searchPlugin({
groups: [
{ slug: 'destinations', label: 'Destinations', limit: 3 },
{ slug: 'stays', label: 'Places to stay', limit: 4 },
// Utility pages are worth finding by name, but not worth suggesting unprompted.
{ slug: 'pages', label: 'Pages', limit: 3, showWhenEmpty: false },
],
collections: [
{ slug: 'regions', group: 'destinations', path: '/regions', weight: 3 },
{
slug: 'hotels',
group: 'stays',
path: '/hotels',
icon: 'bed',
weight: 2,
},
{
slug: 'pages',
group: 'pages',
// Empty string, not undefined: these are served at the site root.
path: '',
excludeSlugs: ['home', 'gift-list'],
},
],
analytics: { retentionDays: 90 },
}),
],
});Endpoints
| Method | Path | Purpose |
| ------ | -------------------------- | ------------------------------------------------------------------- |
| GET | /api/site-search?q= | Grouped, ranked results. Empty q returns the preset. |
| GET | /api/site-search/results | Flat, ranked, paginated: ?q=&collection=&page=&limit=. |
| POST | /api/site-search/reindex | Rebuild the projection now. Returns counts. |
| GET | /api/site-search/inspect | What is indexed, and why anything missing was skipped. |
| POST | /api/site-search/track | Record a settled search and its clicks. Only when analytics are on. |
Change the base with routePrefix. reindex and inspect require an authenticated user unless
you set requireAdminForOperations: false.
Options
| Option | Default | Notes |
| --------------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------- |
| collections | — | Required. Which collections are searchable, and how their results present. |
| groups | — | Required. Presentation buckets, with caps and empty-state opt-in. |
| cacheTTL | 60000 | Milliseconds to hold the projection. |
| fields | title 1, slug 0.4, description 0.2 | Fields matched, with relative weights. |
| fuzzy | { threshold: 0.35, distance: 100, minMatchCharLength: 3 } | Fuse tuning. |
| decodeEntities | true | Decode HTML entities in titles. |
| analytics | false | true, or { retentionDays, collectionSlug }. |
| rateLimit | { limit: 30, window: 60 } | Per-IP limit on the public track endpoint. false disables it. |
| requireAdminForOperations | true | Guard reindex and inspect. |
| indexCollection | search | plugin-search's collection slug, if you renamed it. |
| routePrefix | /site-search | Base path for endpoints. |
| disabled | false | Bypass the plugin entirely. |
Per-collection options
| Option | Notes |
| -------------- | ------------------------------------------------------------------------------------------- |
| slug | Required. The source collection. |
| group | Required. A configured group's slug. |
| path | Required. URL prefix; '' for the site root. |
| weight | Ranking multiplier. Default 1. |
| icon | Opaque token passed through to your icon map. |
| excludeSlugs | Slugs never returned. |
| excludeField | A checkbox on the source collection (e.g. excludeFromSearch) that hides a document. |
| href | (row) => string for URLs path + slug can't express. Gets the raw index row (see below). |
excludeField is read once per projection build, so it costs nothing per request. Toggling it saves
the document, plugin-search re-syncs the row, and the plugin drops its cache, so the change shows
straight away.
For nested URLs (/destinations/asia/indonesia/bali), add the URL to the index row with
plugin-search's beforeSync and a field in searchOverrides, then read it back:
{ slug: 'regions', group: 'destinations', path: '/regions', href: row => row.url as string }Results
Each result carries id, docId (the source document's ID), collection, group, title,
description, href, icon, score and highlights: the matched [start, end) ranges in
title, for bolding the match.
Flat results and filtered archives
GET /api/site-search/results (or service.query()) returns every match ranked and paginated,
ignoring group caps: { docs, totalDocs, page, totalPages, limit }. A listing with its own filters
can use it for fuzzy, ranked matching instead of title: { contains: q }:
const service = createSearchService({
cache: searchIndexCache,
config,
payload,
});
const { docs } = await service.query({
q,
collections: ['hotels'],
limit: 100,
});
const ids = docs.map(d => d.docId);
const hotels = await payload.find({
collection: 'hotels',
where: { and: [{ id: { in: ids } }, ...filters] },
pagination: false,
});
// Restore relevance order: hotels.docs.sort((a, b) => ids.indexOf(String(a.id)) - ids.indexOf(String(b.id)))Caching
The projection is cached in memory for cacheTTL and dropped whenever plugin-search writes the
index, so a published change shows up straight away (on the instance that handled the write; others
wait out the TTL). The cache is one per process: give every createSearchService call the same
config as the plugin, or they will overwrite each other's projection.
A note on minMatchCharLength
The default of 3 is deliberate. Two-character fragments match too much to be useful, and that is
the single most common source of "why is this unrelated thing in my results".
A note on the empty-query preset
presetResults orders by collection weight and then alphabetically. It is not popularity- or
analytics-ranked, and deliberately does not pretend to be — if you want a curated order, set
weights. Once analytics have accumulated, the top-queries report is the honest input for that
decision.
decodeEntities
Content migrated out of a CMS that stored HTML-encoded text (Umbraco, typically) keeps entities in
its titles. Rich-text renderers decode on output, so a page body reads correctly while every
plain-text surface — search results, filter labels, map pins — shows a literal &. Decoding at
projection time fixes all of them at once.
Client helpers
import {
useSearchHotkey,
useIsAppleDevice,
} from '@foundrykit/search-plugin/client';
useSearchHotkey(open); // Cmd+K / Ctrl+KThe hotkey is suppressed inside inputs, textareas, selects and contenteditable. That guard matters:
Ctrl+K is Lexical's "insert link" binding, and Lexical is Payload's own editor.
Headless search hook
'use client';
import { useSiteSearch } from '@foundrykit/search-plugin/client';
const { query, setQuery, results, resultsQuery, loading, error } =
useSiteSearch();
// results: GroupedResults for `resultsQuery`; `loading` until it catches up with `query`.It debounces (250ms), aborts the request a newer keystroke supersedes, and ignores any response
that arrives late, so an older term's results never overwrite a newer one's. Options: endpoint,
debounceMs, initialQuery, or fetcher(q, signal) to call your own route. Outside React,
createSearchRunner does the same, and fetchSiteSearch(q, { endpoint, signal }) is the bare request.
With the advanced search bar
@foundrykit/components' advanced search bar (via @foundrykit/hooks' useAdvancedSearch) takes
onSearch(query) => SearchResult[]. flattenResults turns grouped results into that shape, with the
group label as category and collection, docId, icon and highlights in metadata:
import {
fetchSiteSearch,
flattenResults,
} from '@foundrykit/search-plugin/client';
<AdvancedSearchProvider
onSearch={async q => flattenResults(await fetchSiteSearch(q), groups)}
/>;Pass the same groups you gave the plugin to keep its order and labels.
Analytics and privacy
With analytics on, the search-events collection records one row per settled search: the
query, result count, the results shown, any clicks, the page it happened on, a coarse device type
(mobile, tablet or desktop), the referrer host, and UTM parameters. No IP address and no user
relationship is stored.
- Recording. The browser reports searches to
POST /api/site-search/track. TheGETsearch endpoint no longer records anything. - Rate limit. The track endpoint is public and writes a row per call, so it is limited per
client IP (default 30 a minute, via
@foundrykit/rate-limitand Payload's KV store). SetrateLimit.trustedProxies(e.g.trueon Vercel) or every visitor shares one bucket. visitorCookie(opt-in). Name a cookie and the plugin stores its value on the event, so you can tell repeat searchers apart. The plugin only reads it; your site sets it, and should do so only with consent.isEnabled(req). Returnfalseto skip recording for a request, e.g. when consent is absent.- Retention. Events older than
retentionDays(default 400) are pruned on write, so the log stays bounded without a scheduled job. - Schema change.
clickedHrefis gone and several fields are new. Hosts must generate and run a migration (payload migrate:create).
import { trackSearchEvent } from '@foundrykit/search-plugin/client';
trackSearchEvent({
searchId,
query,
resultCount,
results,
pagePath,
source: 'dialog',
});trackSearchEvent(payload, endpoint = '/api/site-search/track') uses sendBeacon, falls back to a
keepalive fetch, and never throws.
Dashboard
import { SearchDashboard } from '@foundrykit/search-plugin/rsc';A server component showing index counts, skipped documents with reasons, zero-result queries
and top queries. Wire it into admin.components.views or a custom dashboard.
Development
pnpm install
pnpm test:unit
pnpm build
pnpm lint