what-works-global

algolia search

by what-works-global
payload-packages
Search
v3
>=3.39.0 <4

Overview

Summary generated from the README

Syncs Payload collections to an Algolia index, turning each document into a lean text record without per-collection code. It hooks into collection saves, unpublishes and deletes, handles drafts and autosaves, and pushes index settings from config on every reindex. Requires Payload 3.39.0 or newer and Algolia credentials; a headless React entry offers search hooks and highlight components.

Features

  • Extracts text, textarea and rich text values through tabs, groups, arrays and blocks into one content attribute
  • Draft and autosave aware: first drafts are ignored and unpublishing or deleting removes the record
  • Admin header reindex modal, access-controlled endpoint and programmatic runAlgoliaReindex for scripts and cron
  • Atomic full reindexes using replaceAllObjects so search keeps working during a rebuild
  • Index settings managed in code, with per-collection record transforms and field-level include or exclude flags
  • Headless React hooks for search-as-you-type, keyboard navigation, Insights click tracking and Highlight and Snippet…

Use cases

  • Add site-wide quick search to a Payload and Next.js site backed by Algolia
  • Keep an Algolia index in sync with published pages and news while hiding drafts
  • Rebuild the search index from a cron job or admin button after bulk content changes

From the author

Algolia search sync for Payload with draft-aware indexing, a best-effort text extractor that turns any collection into search records with zero per-collection code, admin reindex buttons, and index settings managed as code.

Installation

npm i @whatworks/payload-algolia-search

16

Stars

1

Forks

2

Open Issues

3 days ago

Last Updated

39

Weekly Downloads

v0.2.0

npm Version

193.1 KB

Unpacked Size

1

Dependencies

Repository stars

16+1 since Sep 6

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

Shared by 12 plugins in what-works-global/payload-packages.

npm weekly downloads

38+29 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 202638
Dec 4, 202633
Dec 3, 202625
Dec 2, 202625
Dec 1, 202632
Nov 30, 202631
Nov 29, 202630
Nov 28, 202627
Nov 27, 202635
Nov 26, 202630
Nov 25, 202638
Nov 24, 202631
Nov 23, 202631
Nov 22, 202636
Nov 21, 202635
Nov 20, 202626
Nov 19, 202627
Nov 18, 202619
Nov 17, 202619
Nov 16, 202620
Nov 15, 202629
Nov 14, 202635
Nov 13, 202647
Nov 12, 202660
Nov 11, 202659
Nov 10, 202661
Nov 9, 202662
Nov 8, 202647
Nov 7, 202641
Nov 6, 202632
Nov 5, 202619
Nov 4, 202636
Nov 3, 202633
Nov 2, 202630
Nov 1, 202629
Oct 31, 202629
Oct 30, 202626
Oct 29, 202620
Oct 28, 20262
Oct 27, 20262
Oct 26, 20263
Oct 25, 20264
Oct 24, 20263
Oct 23, 20262
Oct 22, 20266
Oct 21, 20266
Oct 20, 20266
Oct 19, 20266
Oct 18, 20265
Oct 17, 20266
Oct 16, 20266
Oct 15, 20262
Oct 14, 20262
Oct 13, 20264
Oct 12, 20263
Oct 11, 20264
Oct 10, 20264
Oct 9, 20266
Oct 8, 202610
Oct 7, 202615
Oct 6, 202613
Oct 5, 202613
Oct 4, 202615
Oct 3, 202616
Oct 2, 202614
Oct 1, 202612
Sep 30, 20267
Sep 29, 20269
Sep 28, 20269
Sep 27, 20266
Sep 26, 20268
Sep 25, 20268
Sep 24, 20266
Sep 23, 202611
Sep 22, 202610
Sep 21, 202612
Sep 20, 202613
Sep 19, 202611
Sep 18, 202613
Sep 17, 202613
Sep 16, 202611
Sep 15, 202610
Sep 14, 20268
Sep 13, 20267
Sep 12, 20266
Sep 11, 20265
Sep 10, 20265
Sep 9, 20262
Sep 8, 20263
Sep 7, 20264
Sep 6, 20269

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

Health Score

59/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/1064440892-algolia-search.svg)](https://payloaddirectory.dev/plugins/1064440892-algolia-search)
HTML
<a href="https://payloaddirectory.dev/plugins/1064440892-algolia-search"><img src="https://payloaddirectory.dev/badge/1064440892-algolia-search.svg" alt="Payload Directory"></a>
Updated Dec 2, 2026Created Sep 26, 2025Published Jul 14, 2026

README

Algolia Search

 

Algolia search sync for Payload with defaults that hold up in production: draft-aware indexing, a best-effort text extractor that turns any collection into lean search records with zero per-collection code, admin reindex buttons, and index settings managed as code.

  • Best-effort records by default. The plugin walks each collection's field config alongside the document and compresses every text, textarea, and richText value — through tabs, groups, rows, collapsibles, arrays, and blocks — into a single content attribute, in document order. Add a block with a text field and it's searchable the moment an editor saves. title, path, and breadcrumbs come along automatically.
  • Draft- and autosave-aware. First drafts are never indexed, autosaves on top of a published doc don't overwrite the published record, unpublishing/trashing/deleting removes the record. Safe with autosave intervals in the hundreds of milliseconds.
  • Reindex from the admin. An icon in the admin header opens a modal to rebuild the whole index or a single collection, plus an access-controlled endpoint and a programmatic runAlgoliaReindex(payload) for scripts and cron. Full reindexes are atomic (replaceAllObjects) — search keeps working mid-rebuild and stale records are pruned.
  • Index settings live in code. searchableAttributes, snippeting, and faceting are pushed to Algolia on every reindex, so relevance config is reviewable and reproducible instead of hand-edited in the dashboard.
  • Headless frontend search. A /react entry ships useAlgoliaSearch (debounced search-as-you-type, typed to the record shape), useHitCursor (keyboard navigation), useInsights (click/conversion analytics), and dependency-free <Highlight>/<Snippet> components — a complete quick-search UI without react-instantsearch, with zero styling imposed.
  • Serverless-safe. Algolia writes are awaited inside hooks by default, so they aren't frozen when the response is sent.

Demo

Algolia Search reindex button

Algolia Search reindex modal

Installation

pnpm add @whatworks/payload-algolia-search

Requires Payload 3.39.0+ — earlier versions don't pass the request to admin header actions, so the reindex icon's access gate would silently hide it for everyone.

Usage

import { algoliaSearchPlugin } from '@whatworks/payload-algolia-search'
import { buildConfig } from 'payload'

export default buildConfig({
  // ...
  plugins: [
    algoliaSearchPlugin({
      algolia: {
        appId: process.env.ALGOLIA_APP_ID || '',
        apiKey: process.env.ALGOLIA_ADMIN_API_KEY || '', // admin key — server-side only
        index: process.env.ALGOLIA_INDEX || '',
      },
      collections: {
        pages: true,
        news: true,
      },
      getPath: ({ collection, doc }) => getPath(collection.slug, doc),
    }),
  ],
})

Then regenerate the import map so the admin panel can resolve the reindex header action:

payload generate:importmap

Missing credentials don't crash the boot: the plugin logs a warning and pauses sync, while hooks, endpoint, and admin components stay registered so the generated import map is identical across environments.

The record shape

Every document becomes one lean, text-only record:

{
  "objectID": "news:6a45d3f153222a49f8454d1f", // <collection>:<id> — collision-proof across collections
  "collection": "news",
  "title": "Weather info",
  "path": "/news/weather-info",
  "breadcrumbs": ["Learn More", "Weather info"], // only when the doc has a trail
  "content": "…all indexable text, compressed, in document order…",
}
  • title — the collection's useAsTitle field (falls back to doc.title).
  • path — your getPath result, falling back to the last breadcrumb's url (nested-docs stores the full path there).
  • breadcrumbs — nested-docs labels, only when there's more than one (ancestors + own title).
  • content — the best-effort extraction, capped at contentLimit (default 4000 chars) to stay well under Algolia's record size limit.

The matching default index settings (pushed on every reindex):

{
  searchableAttributes: ['title', 'breadcrumbs', 'content'], // order = ranking priority
  attributesToHighlight: ['title', 'breadcrumbs'],
  attributesToSnippet: ['content:20'],
  attributesForFaceting: ['filterOnly(collection)'],
  snippetEllipsisText: '…',
}

With react-instantsearch this gives you title highlighting and a match-centred content excerpt (<Snippet attribute="content" hit={hit} />) with no extra work.

Searching from the frontend

For the common quick-search case you don't need react-instantsearch at all — the /react entry is a headless layer typed to the record shape above, built on the Algolia lite client the package already depends on:

'use client'

import {
  Highlight,
  Snippet,
  useAlgoliaSearch,
  useHitCursor,
  useInsights,
} from '@whatworks/payload-algolia-search/react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'

const appId = process.env.NEXT_PUBLIC_ALGOLIA_APP_ID ?? ''
const indexName = process.env.NEXT_PUBLIC_ALGOLIA_INDEX ?? ''
const searchApiKey = process.env.NEXT_PUBLIC_ALGOLIA_SEARCH_KEY ?? '' // search-only key — never the admin key

export const Search: React.FC = () => {
  const router = useRouter()

  const { query, setQuery, hits } = useAlgoliaSearch({
    appId,
    clickAnalytics: true, // stamp __queryID/__position so clicks are attributable
    indexName,
    searchApiKey,
  })

  const { sendClick } = useInsights({ appId, indexName, searchApiKey })

  const { activeItemRef, cursor, onKeyDown, setCursor } = useHitCursor(hits, {
    onSelect: (hit) => {
      if (hit.path) {
        sendClick(hit)
        router.push(hit.path)
      }
    },
  })

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} onKeyDown={onKeyDown} />
      {hits.map((hit) => (
        <Link
          data-active={hit.objectID === cursor || undefined}
          href={hit.path ?? ''}
          key={hit.objectID}
          onClick={() => sendClick(hit)}
          onMouseEnter={() => setCursor(hit.objectID)}
          ref={hit.objectID === cursor ? activeItemRef : undefined}
        >
          <Highlight attribute="title" hit={hit} />
          {hit.breadcrumbs && <div>{hit.breadcrumbs.join(' / ')}</div>}
          <Snippet attribute="content" hit={hit} />
        </Link>
      ))}
    </div>
  )
}
  • useAlgoliaSearch — debounced search-as-you-type: typed hits, out-of-order responses dropped, no request for an empty query. Options: filters (e.g. 'collection:news'), hitsPerPage, debounceMs, enabled (pause while a modal is closed), clickAnalytics (see useInsights), and raw searchParams. Extra attributes added by a record transform are typed via the generic: useAlgoliaSearch<SearchHit & { section: string }>({ … }).
  • useHitCursor — wrap-around ArrowUp/ArrowDown keyboard cursor, Enter-to-select, and an activeItemRef that keeps the active hit scrolled into view (attach it to the active element only, as above).
  • useInsights — Algolia Insights click/conversion tracking, built on the official search-insights client (an optional peer dependency, loaded lazily the first time the hook runs, so it stays out of bundles that never track — install it only in apps that call useInsights). Returns sendClick(hit) / sendConversion(hit); attach onClick={() => sendClick(hit)} to each result. Combine with useAlgoliaSearch({ clickAnalytics: true }) so hits carry the __queryID/__position that make clicks clickedObjectIDsAfterSearch. search-insights manages the anonymous cookie token (override with a logged-in id via userToken); enabled gates loading and sending on consent.
  • <Highlight> / <Snippet> — render _highlightResult/_snippetResult as React nodes, matches wrapped in <mark> — no dangerouslySetInnerHTML. Style via className/highlightedTag; array attributes like breadcrumbs are joined with separator. Snippeting content works out of the box because the plugin's default index settings request it.

Everything is unstyled — the components render a single <span> and you own all surrounding markup. If you need facets or pagination, reach for react-instantsearch instead; the records and index settings work with it as-is.

Controlling what gets indexed

Global and per-collection exclude lists. By default these field names are skipped at any depth: slug, meta (the SEO plugin's group), metadata, breadcrumbs, filename, mimeType, url, thumbnailURL, apiKey — plus each collection's useAsTitle field, which is indexed separately as title. Entries match a field name at any depth ('internalNotes') or a dot-path from the document root ('hero.eyebrow').

import { algoliaSearchPlugin, defaultExcludeFields } from '@whatworks/payload-algolia-search'

algoliaSearchPlugin({
  // ...
  excludeFields: [...defaultExcludeFields, 'legalDisclaimer'], // global (replaces the default list)
  collections: {
    pages: true,
    news: {
      excludeFields: ['slug', 'excerpt'], // replaces the effective list for news only
    },
  },
})

Field-level flags beat every list. On any field:

{
  name: 'internalNotes',
  type: 'textarea',
  custom: { algoliaSearch: false }, // never indexed
},
{
  name: 'region',
  type: 'select', // non-text types are skipped by default…
  custom: { algoliaSearch: true }, // …unless opted in (value is stringified)
  options: [...],
}

Per-collection record shaping. The record transform receives the default record and the doc — typed from your generated Payload types for that collection. Return undefined to keep the default, a record to index (spread defaultRecord to extend), or null to keep the doc out of the index entirely — existing records are removed, so a hideFromSearch checkbox works retroactively:

collections: {
  pages: {
    record: ({ defaultRecord, doc }) => {
      if (doc.hideFromSearch) return null
      return { ...defaultRecord, section: doc.section }
    },
  },
},

Rich text. Lexical states go through the official convertLexicalToPlaintext when @payloadcms/richtext-lexical is installed (it's an optional peer). Pass richTextConverters to teach it custom nodes (e.g. blocks inside rich text), or replace extraction entirely with richTextToText: (value) => string. Without the package, a dependency-free extractor collects text nodes from Lexical and Slate states alike, including stringified ones.

Reindexing

  • Admin header action — an icon next to the other header controls opens the reindex modal: rebuild everything atomically, reindex one collection at a time, and see per-collection record counts as runs finish. Hide it for everyone with reindex.button: false.

  • Endpoint — POST /api/algolia-search/reindex (all collections, atomic) or POST /api/algolia-search/reindex?collection=pages. Default access: any authenticated user; override with reindex.access, which both guards the endpoint and decides whether a given user sees the header icon.

  • Programmatic — from a script, migration, or cron job:

    import { runAlgoliaReindex } from '@whatworks/payload-algolia-search'
    
    const result = await runAlgoliaReindex(payload) // or (payload, { collection: 'pages' })
    // { indexed: { pages: 42, news: 128 }, mode: 'all', total: 170 }
    

Only published documents are fetched for drafts-enabled collections; trashed documents are skipped.

All options

algoliaSearchPlugin({
  // appId / apiKey / index may be undefined (e.g. straight off process.env) —
  // sync pauses with a warning until they're set
  algolia: { appId, apiKey, index, clientOptions? },

  collections: {
    pages: true,  // defaults
    drafts: false, // same as omitting — handy for conditional config
    news: {
      excludeFields?: string[],       // replace the effective exclude list
      contentLimit?: number,          // per-collection content cap
      getPath?: ({ collection, doc, req }) => string | null | undefined, // override the global getPath
      record?: ({ collection, doc, req, defaultRecord }) => record | null | undefined,
      // ^ doc is typed from your generated Payload types in both callbacks
    },
  },

  getPath?: ({ collection, doc, req }) => string | null | undefined,
  excludeFields?: string[],           // replace defaultExcludeFields
  contentLimit?: number,              // default 4000
  awaitSync?: boolean,                // default true — await Algolia writes in hooks (see below)
  waitUntil?: (promise) => void,      // scheduler for background writes when awaitSync: false (auto-detected on Vercel)
  enabled?: boolean,                  // false returns the config untouched
  indexSettings?: IndexSettings | false, // merged over defaultIndexSettings; false = never write
  richTextConverters?: {...},         // forwarded to convertLexicalToPlaintext
  richTextToText?: (value) => string, // replace rich text extraction

  reindex?: boolean | {               // true/omitted = defaults, false disables all of it
    path?: string,                    // default '/algolia-search/reindex'
    access?: ({ req }) => boolean | Promise<boolean>, // guards the endpoint + header icon; default: any authenticated user
    batchSize?: number,               // default 100
    depth?: number,                   // default 0
    button?: boolean,                 // false hides the admin header icon
  },
})

Blocking vs background sync (awaitSync)

By default hooks await the Algolia write, so every save waits one Algolia round trip. That is durable everywhere, which is why it's the default. Set awaitSync: false to let saves return immediately and sync in the background — but only where background work is guaranteed to finish:

  • Vercel — works out of the box; no waitUntil option needed:

    algoliaSearchPlugin({
      // ...
      awaitSync: false, // that's it — waitUntil is picked up automatically
    })
    

    The plugin reads the runtime's request context (Symbol.for('@vercel/request-context') — the same global @vercel/functions reads) and hands the write to its waitUntil, which keeps the invocation alive until the write lands without delaying the response. Passing the official @vercel/functions export via the waitUntil option also works, but is redundant.

  • Long-lived servers (Docker, VPS, next start self-hosted) — safe; the process outlives the request anyway.

  • Other platforms with a waitUntil primitive — pass it via the waitUntil option, e.g. Cloudflare Workers via OpenNext: waitUntil: (p) => getCloudflareContext().ctx.waitUntil(p).

  • Runtimes that freeze after the response (bare AWS Lambda and anything built on it) and scripts that exit immediately (seeds using the Local API) — keep the default. There is no after-response hook to attach to, so background writes can be silently dropped.

The promise handed to waitUntil never rejects — sync failures are logged through payload.logger either way.

How draft handling works

EventIndex action
First draft (never published)ignored
Autosave/draft save over a published docignored — published record stays live
Publish / restore published versionrecord saved
Unpublish (no published version remains)record removed
Trash (deletedAt)record removed
Permanent deleterecord removed
Collection record transform returns nullrecord removed

Sync failures never block a save — errors are logged through payload.logger and the document operation succeeds.

Credits

Draft/unpublish semantics adapted from payload-plugin-algolia by Will Kent-Daggett (MIT).

Similar plugins