🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Query optimization for Next.js build with Sanity.io

4 replies
Last updated: Feb 8, 2024
Hey y’all. A little panicked about our Sanity requests timing out during Next.js build.
I have this query


*[
        _type == "trip" &&
        contentSv->slug.current == "royal-national-hotel"
      ] {
        _id,
      }[0]
Normally it has more fields in it, but I would like to know if it’s possible to speed this query up in any way?
We need to fetch by slug, we can’t use the _id in Sanity.

There’s about 4000 entries like this.
Feb 8, 2024, 10:39 AM
Good to know is that contentSv is a
tripContent
entry, and it has a one-to-one relationship with the
trip
type
Feb 8, 2024, 10:42 AM
OK, I think I found a way to speed it up.

*[
        _type == "tripContent" &&
        slug.current == "royal-national-hotel"
      ] {
        _id,
        ...(*[references(^._id)][0] {
          // what I need from the parent
        })
      }[0]
Feb 8, 2024, 10:45 AM
OK, this reduced the query to run in milliseconds.

*[
        _type == "tripContent" &&
        slug.current == "royal-national-hotel" &&
        count(*[_type == "trip" && contentSv._ref == ^._id]) > 0
      ] {
        ...(*[_type == "trip" && contentSv._ref == ^._id][0] {
          _id,
          "headline": ^.headline,
          "description": ^.description,
          "salesPitch": ^.salesPitch,
          // ... other stuff
        })
      }
Feb 8, 2024, 11:12 AM
Thank you for sharing your soluition.
Feb 8, 2024, 5:36 PM

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?