sanity-algolia
v1.1.0
Published
Here are some helpers to facilitate indexing your Sanity documents as Algolia records, via custom serializing, optional hidden/visibility filtering and directly syncing to an Algolia index from a Sanity webhook.
Downloads
30,732
Readme
Sanity + Algolia = ♥️
Here are some helpers to facilitate indexing your Sanity documents as Algolia records, via custom serializing, optional hidden/visibility filtering and directly syncing to an Algolia index from a Sanity webhook.
Steps to implement
- Set up one or more webhooks on Sanity to trigger when content is created, edited or deleted.
- Deploy a serverless function to receive the webhook payload and update Algolia index
Setup webhook
This is an example of indexing Sanity content in Algolia directly from a Sanity webhook. The target of the webhook is a serverless function running on Vercel, Netlify, AWS etc.
Set up the following Webhook on Sanity. It needs to be that specific webhook projection at the moment, as this module is not yet updated to take advantage of the new GROQ powered Webhooks. You should configure your webhook to target the URL of the serverless function once deployed.
Deploy serverless function
See examples in the example/
folder in this repository for how this can be
done. You will want to tailor this code to your own content types and fields,
and do any transformation on your data before its indexed in Algolia.
Note that your serverless hosting might require a build step to properly deploy your serverless functions, and that the exported handler and passed parameters might differ from the included examples. Please refer to documentation on deploying functions at your hosting service of choice in order to adapt it to your own needs.
First time indexing
The webhook is great for keeping Algolia up to date to new changes in your
Sanity datasets, but you likely also want to first index any content you already
have. The simplest way to do this is to run the sanityAlgolia.webhookSync
method manually. For ease of use you can export the sanity client and the
sanityAlgolia objects from your handler file exemplified above and make use of
them like this
const sanity = ...; // configured Sanity client
const sanityAlgolia = ...; // configured sanity-algolia
// Fetch the _id of all the documents we want to index
const types = ["article", "page", "product", "author"];
const query = `* [_type in $types && !(_id in path("drafts.**"))][]._id`
sanity.fetch(query, { types }).then(ids =>
sanityAlgolia.webhookSync(sanity, { ids: { created: ids, updated: [], deleted: [] }})
)