How to fetch an array of images using groq in Sanity.io
The issue with your query is that you need to match the field name from your schema. Looking at your code, there's a mismatch between what you defined in your schema and what you're querying.
Your schema defines the field as:
name: "image", // This is the field nameBut you're querying images[] (with an 's'). You should query image[] to match your schema:
return client.fetch(
groq`*[_type == 'page' && slug.current == $slug][0]{
_id,
_createdAt,
"mainImage": mainImage.asset->url,
"images": image[].asset->url, // Changed from images[] to image[]
title,
"slug": slug.current,
content,
alt
}`,
{slug}
)The syntax image[].asset->url is correct - it:
- Maps over each item in the
imagearray - Dereferences the
assetreference using-> - Extracts the
urlfield from each asset
I've aliased it as "images" (plural) in the projection for clarity in your returned data, but the important part is reading from the correct image field name.
If you're still getting null after fixing this, check:
- That your documents actually have images in the
imagefield (check in Sanity Studio) - That the images are properly uploaded with asset references
- That you're querying published documents (drafts have
_idstarting with "drafts.")
You can also get more image data by expanding the projection:
"images": image[]{
"url": asset->url,
"alt": alt,
"hotspot": hotspot
}This gives you an array of objects with URL, alt text, and hotspot information for each image.
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.