How to expand image asset references in PortableText/BlockContent with GROQ?
When querying PortableText with image references, you need to use GROQ's conditional operator and the @ operator to expand inline references. Here's how to solve this:
The Solution
Use this GROQ query pattern to expand image references within your PortableText blocks:
*[_type == "post"] {
title,
body[]{
...,
_type == "image" => {
...,
"asset": @.asset->
}
}
}How It Works
The key is using the @ operator, which refers to the root value of the current scope. When you iterate through the PortableText array with body[], the @ operator lets you access the current block object and dereference its asset.
Breaking it down:
body[]- Iterates through all blocks in your PortableText array...- Spreads all existing properties of each block_type == "image" => {...}- Conditionally handles blocks that are images@.asset->- Dereferences the asset for the current image block
For Custom Reference Types
If you have custom reference types in your PortableText (like in the children array), use the same pattern:
children[]{
...,
_type == 'orderReceiptPlaceholderRef' => {
"reference": @->
}
}This approach works because:
- Some children are regular spans, others are references
children[]->would dereference everything (leaving non-references as null)children[]alone includes everything but doesn't expand references- Using the conditional with
@->only dereferences when needed
You can find more examples of GROQ conditionals in the GROQ query cheat sheet, and this solution is based on a community discussion about this exact issue.
Show original thread7 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.