Gatsby - Contentful - Algolia Search Image Webhook

My Gatsby/Contentful blog is using Algolia to search through blog posts. Everything is working just fine, besides displaying images.

I cant get the images working.

This is the Webhook Payload that Ive created in Contentful by using the Algolia template:

{
“title”: “{ /payload/fields/title/en-US}”,
“slug”: “{ /payload/fields/slug/en-US}”,
“price”: “{ /payload/fields/price/en-US}”,
“category”: “{ /payload/fields/category/en-US}”,
“usages”: “{ /payload/fields/usages/en-US}”,
“rating”: “{ /payload/fields/rating/en-US}”,
“image”: “https:{ /payload/fields/image/fields/file/url}”
}

My algolia query looks like this:

algolia.js

const contentfulQuery =
{
allContentfulStrains {
nodes {
id
title
price
category
image {
file {
url
}
}
}
}
}

function pageToAlgoliaRecords({ id, title, price, image }) {
return { objectID: id, title, price, image }

}

const queries = [
{
query: contentfulQuery,
transformer: ({ data }) => data.allContentfulStrains.nodes.map(pageToAlgoliaRecords),
}
]

module.exports = queries

Now when I type gatsby build the data algolia is receiving is not structured right. View the image below. I want the structure to be - image:image.url so I can get the url of the image and past it in the hit component to display the images.

Is there something wrong with my query?

I hope someone can help me… im so frustrated and cant find a solution

Hi Patrick!

This is more of a Gatsby/GraphQL question than an Algolia one, so I would recommend looking into their documentation to understand more when you have trouble with constructing GraphQL queries.

Now, from what I’m seeing of your current, query, the image property of your contentfulQuery query is not the URL, but an object that contains it ({ file: { url: string } }). Therefore, in your pageToAlgoliaRecords function, instead of adding the full image object to your Algolia record, you need to walk the object and retrieve the URL:

function pageToAlgoliaRecords({ id, title, price, image }) {
  return { objectID: id, title, price, image: image.file.url };
}

Note that if you don’t want to change your function, Algolia fully supports nested attributes. Nothing prevents you from retrieving the nested image object and displaying the nested url property with React InstantSearch in your Gatsby website:

const Hits = ({ hits }) => (
  <ol>
    {hits.map((hit) => (
      <li key={hit.objectID}>
        <img src={hit.image.file.url} />
      </li>
    ))}
  </ol>
);

Hope this helps!

omg omg! Its working now!!! Thank you endless <3

Hey, Patrick! May I ask you how did you include a file into your webhook here “image”: “https:{ /payload/fields/image/fields/file/url}”? Contentful doesn’t send a file in my payload and just output undefined.

Hi, Have you tried Gatsby build?

Thanks for the reply! Yes, indeed, I’ve ended up using gatsby build plugin instead! It works just great. Good luck with your project! :innocent: