Discussion on getting an array of images from Sanity for a gallery page in Next.js, with tips on code formatting and content strategy.
Happy New Year! The issue you're experiencing is likely because imgUrl is either not an image type field, or you're trying to reference it incorrectly. Let me help you fix this.
The problem is in how you're dereferencing the asset. When you have an image field in Sanity, it's stored as a reference object, and you need to properly traverse it to get the URL.
Your query actually looks correct syntactically! So the issue is likely one of these:
1. The field name might be different
Check your schema - is the image field actually called imgUrl? It might be image, mainImage, or something else.
2. Some documents might not have images If some gallery documents don't have an image, you'll get null for those. You can filter them out:
const query = groq`*[_type == "gallery" && defined(imgUrl.asset)]{
"url": imgUrl.asset->url,
title,
description,
projectLink,
codeLink,
tags
}`3. You need the full image URL If you're getting an object instead of a string, you might need to use Sanity's image URL builder. Here's a better approach:
import imageUrlBuilder from '@sanity/image-url'
const builder = imageUrlBuilder(client)
export const getStaticProps = async () => {
const query = groq`*[_type == "gallery" && defined(imgUrl)]{
imgUrl,
title,
description,
projectLink,
codeLink,
tags
}`
const data = await client.fetch(query)
// Transform the data to include proper URLs
const dataWithUrls = data.map(item => ({
...item,
url: item.imgUrl ? builder.image(item.imgUrl).url() : null
}))
return {
props: { data: dataWithUrls }
}
}The image URL builder approach is the recommended way because it gives you access to all of Sanity's image transformation capabilities and handles the asset reference properly.
If you just want an array of URLs (not the full objects), you can simplify it:
const query = groq`*[_type == "gallery" && defined(imgUrl.asset)].imgUrl.asset->url`This will return just an array of URL strings directly. The key is using .imgUrl.asset->url at the end of the projection to extract just those values into a flat array.
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.