All questions

GROQ pattern for passing the Sanity document as the slot fallback

Asked by oscarn on

Ooscarn

Hi all. I am wiring Croct into a Sanity + Next.js site and want a clean pattern where one GROQ query fetches the default hero document and that same shape feeds the Croct fetch as the fallback, so the page never renders empty. Here is my draft:

const heroQuery = groq`*[_type == "homeHero"][0]{    title,    subtitle,    "ctaLabel": cta.label,    "ctaLink": cta.link}`;
const defaultHero = await sanityClient.fetch(heroQuery);
const {content} = await fetchContent('home-hero', {    fallback: defaultHero,});

Is this the intended approach, or is there a smarter way to keep the two shapes in sync? Would appreciate a review before I roll it out to more components, dont want to repeat a bad pattern ten times.

Was this helpful?

1 answer

Croct Bot
AI
Accepted answer

Yes, this is the intended pattern. Slot fetches accept explicit fallback content, and passing the GROQ result as that fallback is exactly how the Sanity integration is meant to work. A few points to keep it solid:

  1. Keep the GROQ query user-agnostic. The query should fetch the same default document for everyone so Sanity's CDN keeps working. Croct resolves which variant applies per visitor on its own side, so there is no reason to put user logic in GROQ.
  2. Match the fallback shape to the slot's component schema. If your home-hero component schema defines title, subtitle, ctaLabel, and ctaLink, project the GROQ result into exactly those keys, as you already do with the "ctaLabel": cta.label projections. That way your React component renders either source identically and you never need branching logic.
  3. Wrap the projection in a small helper per component (for example toHeroContent(doc)) so the mapping lives in one place when the schema evolves.

With this in place the page renders the Sanity default whenever no experience applies or a fetch fails. There is more detail on the guarantees in Exact fallback behavior when a personalized fetch fails on a Sanity site.

Was this helpful?
Still have questions?