Querying a single field from a Sanity schema using groq in Node.js
No worries, this is a common question when you're getting started with GROQ! The good news is your query is actually really close – you just need to simplify it a bit.
You can absolutely include the .asset->url reference directly in your projection. Here's how to write it:
const query = groq`*[_type == "siteSettings"]{ "image": gigs_image.asset->url }`;
const result = await client.fetch(query).catch(error => console.error(error));Or if you want the first (and likely only) siteSettings document:
const query = groq`*[_type == "siteSettings"][0]{ "image": gigs_image.asset->url }`;
const result = await client.fetch(query).catch(error => console.error(error));What's happening here:
The -> operator in GROQ is called the dereference operator, and it follows references to other documents. When you have an image field in Sanity, it stores a reference to an asset document. Using gigs_image.asset->url tells GROQ to:
- Get the
gigs_imagefield - Follow the reference in
assetto the actual image asset document - Return the
urlfield from that asset
A few tips:
- You don't need to split your filter and projection into separate variables – GROQ queries work as a single pipeline as explained in the projections documentation
- The quotes around
"image"create an alias for the field in your result (so you get{ image: "https://..." }instead of{ url: "https://..." }) - If you want the full image object with metadata, you could use
gigs_image.asset->without the.urlat the end - Since
*[_type == "siteSettings"]returns an array, adding[0]gets you the first document directly, which is cleaner if you only have one settings document
Hope this helps! GROQ's reference following with -> is super powerful once you get the hang of it.
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.