How to grab image metadata from images inserted into Content blocks?
You can expand references inside Portable Text blocks, including image assets, by using GROQ's reference access operator (->) to dereference them in your query.
When you have images in your Portable Text content blocks, they're stored as references to asset documents. To get the full image metadata (dimensions, palette, LQIP, etc.), you need to expand those references when querying.
Here's how to do it:
*[_type == "article"]{
body[]{
...,
_type == "image" => {
...,
asset->
}
}
}This query:
- Iterates through each item in the
bodyarray withbody[] - Uses the spread operator
...to include all existing properties - Conditionally expands image blocks with
_type == "image" => - Dereferences the asset with
asset->to get the full asset document including metadata
If you only need specific metadata fields, you can project them:
*[_type == "article"]{
body[]{
...,
_type == "image" => {
...,
asset->{
_id,
url,
metadata {
dimensions,
palette,
lqip
}
}
}
}
}This also works for references in markDefs (like link annotations). For example, if you have reference annotations in your Portable Text:
*[_type == "article"]{
body[]{
...,
markDefs[]{
...,
_type == "internalLink" => {
...,
reference->
}
}
}
}The reference access operator documentation has more details on joining asset documents in Portable Text queries. The key is using the -> operator after any reference field to fetch the complete referenced document instead of just getting back the _ref ID.
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.