Error: unable to resolve image URL from source (undefined)
This error happens because you're passing undefined (or a null/missing value) to the @sanity/image-url builder, and it can't generate a URL from a non-existent image reference.
Common causes:
- The image field is optional and hasn't been set - Check if your document actually has an image uploaded for that field
- Incorrect field path - You might be accessing the wrong property (e.g.,
imageinstead ofmainImage) - Missing nested property - Trying to access
image.assetwhenimageitself is undefined
Quick fix with optional chaining:
import { urlFor } from './imageUrlBuilder'
// Add a conditional check
{post.mainImage && (
<img src={urlFor(post.mainImage).width(800).url()} alt={post.title} />
)}
// Or provide a fallback
<img
src={post.mainImage ? urlFor(post.mainImage).width(800).url() : '/placeholder.png'}
alt={post.title}
/>Debug by checking your data:
console.log('Image data:', post.mainImage)
// Should show something like: { _type: 'image', asset: { _ref: 'image-abc123...', _type: 'reference' } }If it shows undefined, the image either hasn't been uploaded in Sanity Studio or your GROQ query isn't fetching it correctly. Make sure your query includes the image field:
*[_type == "post"] {
title,
mainImage, // Make sure this is included
// ... other fields
}The @sanity/image-url package expects a valid SanityImageSource object with an asset reference - it can't work with undefined values. Always validate that your image data exists before passing it to the URL builder.
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.