Conditional selection of image and returning a reference if the _type is image, otherwise returning the rest of the available fields.
Yes, this is definitely possible in GROQ! You can use conditional projections combined with the ellipsis operator (...) to achieve this. The ellipsis operator includes all fields from the current document, which is perfect for your "return everything else" scenario.
Here's how to structure your query:
content[]{
_type == 'image' => {
altText,
caption,
"image": asset->url
},
_type != 'image' => {
...
}
}This approach uses two conditional projections:
- When
_typeis'image', it returns your custom projection withaltText,caption, and the resolved image URL - When
_typeis NOT'image', the ellipsis operator (...) includes all fields from that document
The ellipsis operator is syntactic sugar that expands to include all attributes from the current document. It's evaluated first regardless of position, so you can also combine it with additional fields if needed.
Alternative approach - if you want to always include certain base fields plus conditional ones:
content[]{
...,
_type == 'image' => {
"image": asset->url
}
}This keeps all original fields and adds the resolved image URL only when the type is 'image'.
One thing to watch out for: if you place the ellipsis after other field definitions, it can override them since the ellipsis is always evaluated first. The ellipsis operator documentation explains this behavior in detail - when multiple keys with the same name exist, the latest wins, except the ellipsis is always evaluated first.
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.