Discussion on resolving an error with image URLs in a Next.js app using @sanity/image-url library.
This error occurs when you're trying to generate an image URL using the @sanity/image-url library, but the data structure being passed doesn't match what the library expects. Based on the error message showing an array structure, here are the most common causes and solutions:
1. Passing an array instead of the image object
Your error shows the image data wrapped in square brackets [{...}], indicating it's an array. The urlFor() function expects an object, not an array:
// ❌ Wrong - passing an array
urlFor([imageData])
// ✅ Correct - passing the object directly
urlFor(imageData)2. Image field is defined as an array in your schema
If your image field is actually an array type in your Sanity schema, you need to access a specific image from that array or map through it:
// If image is an array, access the first image
urlFor(product.image[0])
// Or map through all images
{product?.image?.map(img => (
<img key={img._key} src={urlFor(img).url()} />
))}3. Not expanding the asset reference in your GROQ query
According to the Sanity documentation on presenting images, you need to expand the asset reference in your query:
// ❌ Wrong - doesn't expand the reference
*[_type == "post"] {
title,
image
}
// ✅ Correct - expands the asset reference
*[_type == "post"] {
title,
image {
asset->
}
}4. Handling undefined values
Always check that the image data exists before trying to generate a URL:
{product.image?.asset && (
<img src={urlFor(product.image).url()} alt={product.title} />
)}Expected data structure
The @sanity/image-url library expects an object with an asset property containing either a reference or the full asset object:
// With reference
{
asset: {
_ref: "image-85fd403b...",
_type: "reference"
}
}
// Or with expanded reference (using asset-> in query)
{
asset: {
_id: "image-85fd403b...",
url: "...",
// other asset properties
}
}Based on a community discussion that resolved this exact issue, the most common solution is:
- Update your GROQ query to properly expand the asset reference using
asset-> - If your image field is an array, map through it properly with a return statement
- Ensure you're not accidentally wrapping the image data in an array or passing undefined values to
urlFor()
The working code pattern looks like this:
{products?.map(product => (
<div key={product._id}>
<h1>{product?.title}</h1>
{product?.image?.map(image => (
<img key={image._key} src={urlFor(image).url()} alt="" />
))}
</div>
))}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.