Accessing referenced document data in Gatsby from Sanity reference field
I can see your issue! You're getting the _ref but not the actual referenced document data. This is a common challenge when working with Sanity references in Gatsby.
The key is that gatsby-source-sanity actually resolves references for you automatically in GraphQL queries, but you need to explicitly request the fields you want in your GraphQL query. The reference data won't be available in your component props unless you query for it.
Here's how to fix it:
In your GraphQL query (in your page or template file), you need to expand the reference like this:
query {
# your query here
sanityYourDocType {
featuredPost {
post {
# These are the fields from the referenced document
_id
title
slug {
current
}
# add any other fields you need from the referenced doc
}
}
}
}The gatsby-source-sanity plugin automatically resolves references when you query through GraphQL - you just need to specify which fields you want from the referenced document.
Alternative approach using _rawPost:
If you need deeper reference resolution or are working with Portable Text that contains references, you can use the special _raw fields that gatsby-source-sanity generates:
query {
sanityYourDocType {
_rawFeaturedPost(resolveReferences: { maxDepth: 5 })
}
}The _raw fields give you the complete raw data from Sanity with references resolved to the depth you specify. This is particularly useful for complex nested references.
Why you're only seeing _ref:
When you don't explicitly query for the referenced document's fields in GraphQL, Gatsby only gives you the reference stub (the _ref field). The actual document data exists in Gatsby's data layer, but you need to tell GraphQL to fetch and join it.
Once you update your GraphQL query to include the fields you need, your component code should work as-is - postId.title will be available because the reference will be fully resolved in your props.
Show original thread66 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.