👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Error integrating Algolia with NextJS and Sanity

6 replies
Last updated: Jan 24, 2022
Hello, I am trying to integrate algolia on one my NextJS project. I was trying to sync with
sanity-algolia
via Next API but I keep getting error
error - TypeError: Cannot read property 'created' of undefined
    at _callee$ (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:891:57)
    at tryCatch (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:129:40)
    at Generator.invoke [as _invoke] (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:359:22)
    at Generator.next (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:184:21)
    at asyncGeneratorStep (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:29:24)
    at _next (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:51:9) {
  page: '/api/sanityAlgolia'
}
Nov 3, 2021, 2:29 AM
Here is my current file looks like

import sanityClient from "@sanity/client";
import algoliasearch from "algoliasearch";
import { NextApiRequest, NextApiResponse } from "next";
import indexer from "sanity-algolia";

const algolia = algoliasearch(
  process.env.NEXT_PUBLIC_ALGOLIA_APPID,
  process.env.ALGOLIA_ADMINKEY
);
const sanity = sanityClient({
  projectId: process.env.NEXT_PUBLIC_PROJECTID,
  dataset: process.env.NEXT_PUBLIC_DATASET,
  apiVersion: "v2021-03-25",
  token: process.env.SANITY_TOKEN,
  useCdn: false,
});

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.headers["content-type"] !== "application/json") {
    res.status(400);
    res.json({ message: "Bad request" });
    return;
  }
  try {
    const sanityAlgolia = indexer(
      // The first parameter maps a Sanity document type to its respective Algolia
      // search index. In this example both `post` and `article` Sanity types live
      // in the same Algolia index. Optionally you can also customize how the
      // document is fetched from Sanity by specifying a GROQ projection.
      {
        news: {
          index: algolia.initIndex("news"),
          projection: `{
            title,
            "slug": slug.current,
            "body": pt::text(body)
          }`,
        },
        page: {
          index: algolia.initIndex("pages"),
          projection: `{
            title,
            "slug": slug.current,
            "body": pt::text(body)
          }`,
        },
        service: {
          index: algolia.initIndex("services"),
          projection: `{
            name,
            "slug": slug.current,
            "text": section1.short_description
          }`,
        },
        physician: {
          index: algolia.initIndex("physicians"),
        },
        staff: {
          index: algolia.initIndex("staff"),
        },
        location: {
          index: algolia.initIndex("locations"),
        },
        patientForm: {
          index: algolia.initIndex("patientForms"),
        },
      },
      // The second parameter is a function that maps from a fetched Sanity document
      // to an Algolia Record. Here you can do further mutations to the data before
      // it is sent to Algolia.
      (document) => {
        return document;
      }
    );
    console.log(req.body);
    return sanityAlgolia
      .webhookSync(sanity, req.body)
      .then(() => res.status(200).send("ok"));
  } catch (error) {
    return error;
  }
}
Nov 3, 2021, 2:35 AM
There are couple things I would like to note that. I have tried console.log the
req.body
but it doesn’t give the format as
sanityAlgolia.webhookSync
wants.
webhookSync
want to return
ids: {
        created: string[];
        updated: string[];
        deleted: string[];
    };
But I am just sending
req.body
as github stated
Nov 3, 2021, 2:44 AM
Hey Shoaib! I think you're running into an issue with that Algolia package relying on Sanity's legacy webhooks. About a month ago, we switched to the new GROQ Powered Webhooks. You can't re-enable the legacy behavior, but you can mimic the old behavior using the method in the changelog .
Nov 3, 2021, 6:22 PM
Thank you
user M
, I am wondering if there is a way we know how to detect whether the webhook is for (created or updated or deleted)
Nov 3, 2021, 6:39 PM
Thank you
user M
, I am wondering if there is a way we know how to detect whether the webhook is for (created or updated or deleted)
Nov 3, 2021, 6:39 PM
user K
Were you able to resolve the above issue? 😊
Jan 24, 2022, 6:40 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?