GROQ query inside document preview to check bidirectional reference

6 replies
Last updated: Nov 29, 2025
Hi all, anyone ever run some groq inside a document preview? Inside a reference field I need to add a flag to illustrate whether the referenced document also references the current document 🙃.

preview: {
    select: {
      title: 'title',
      subtitle: 'type',
      type: 'type',
    },
    prepare({ title = 'Untitled', type, subtitle }) {
      const sub = // groq - does this doc reference the parent doc?;
      return {
        title,
        subtitle: sub,
        media: eosIcon,
      };
    },
  },
AI Update

Unfortunately, you cannot run GROQ queries directly inside the prepare function of a preview configuration. The prepare function is synchronous and doesn't have access to the Sanity client or the ability to make additional queries. This is a known limitation mentioned in the Sanity documentation.

However, you have a couple of alternatives to achieve what you're trying to do:

You can create a custom preview component that can use the Sanity client to fetch additional data:

import { PreviewProps } from 'sanity'
import { useClient } from 'sanity'
import { useEffect, useState } from 'react'

const CustomReferencePreview = (props: PreviewProps) => {
  const client = useClient({ apiVersion: '2024-01-01' })
  const [hasBackReference, setHasBackReference] = useState(false)
  const documentId = props.documentId
  const parentId = /* you'll need to pass this somehow */

  useEffect(() => {
    const checkBackReference = async () => {
      const result = await client.fetch(
        `*[_id == $documentId && references($parentId)][0]`,
        { documentId, parentId }
      )
      setHasBackReference(!!result)
    }
    
    checkBackReference()
  }, [documentId, parentId, client])

  return props.renderDefault({
    ...props,
    subtitle: hasBackReference ? '↔️ Mutual reference' : props.subtitle
  })
}

// In your schema
{
  name: 'myReference',
  type: 'reference',
  components: {
    preview: CustomReferencePreview
  }
}

Option 2: Pre-compute the Flag with Sanity Functions

If this relationship is important, consider adding a field that gets updated when the relationship changes. You could use Sanity Functions with a document mutation event handler to automatically update this flag whenever documents are linked:

// In sanity.blueprint.ts
export default defineBlueprint({
  functions: [
    {
      name: 'update-mutual-references',
      handler: './functions/updateMutualReferences.ts',
      on: {
        mutation: {
          documentTypes: ['yourDocumentType']
        }
      }
    }
  ]
})

Option 3: Select from a Computed Field

If you add a computed field to your document that tracks mutual references, you can select it in your preview:

preview: {
  select: {
    title: 'title',
    hasMutualReference: 'mutualReferenceFlag' // pre-computed field
  },
  prepare({ title, hasMutualReference }) {
    return {
      title,
      subtitle: hasMutualReference ? '↔️ Mutual' : 'One-way →'
    }
  }
}

The custom preview component (Option 1) is probably your best bet for dynamic checking, though be aware it will make queries for each preview rendered, which could impact performance with many items. The Sanity Functions approach (Option 2) would be more performant as it pre-computes the relationship, but requires more setup.

Show original thread
6 replies

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?