Passing undefined to Sanity image URL builder causes error

12 replies
Last updated: Jan 27, 2026
Because you’re passing
undefined
to the image URL builder, and it does not like that.
AI Update

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:

  1. The image field is optional and hasn't been set - Check if your document actually has an image uploaded for that field
  2. Incorrect field path - You might be accessing the wrong property (e.g., image instead of mainImage)
  3. Missing nested property - Trying to access image.asset when image itself 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.

Show original thread
12 replies

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.

Was this answer helpful?