How to render Sanity images in Next.js using file.asset._ref?
file.asset._refbut the image remains broken, I've tried multiple aproaches like @sanity/image-url or constructing the url manually or placing directly the filename as it's coming from server, without any luck.
Does anyone can help with this?
It sounds like you're having trouble rendering images from Sanity in Next.js. The issue is likely that you're trying to use file.asset._ref directly, but this reference needs to be resolved to get the actual image URL.
Here are the most common solutions:
1. Use GROQ to get the URL directly
In your GROQ query, use the -> operator to dereference the asset and get its URL:
*[_type == 'yourType']{
name,
"imageUrl": image.asset->url
}This will give you the full CDN URL that you can use directly in an <img> tag.
2. Use @sanity/image-url (Recommended)
The @sanity/image-url library is the best way to handle Sanity images as it automatically respects crop and hotspot settings:
Install it:
npm install @sanity/image-urlSet up a helper function:
// lib/sanityImageUrl.ts
import { createImageUrlBuilder } from '@sanity/image-url'
import { client } from './sanity' // your sanity client
const builder = createImageUrlBuilder(client)
export function urlFor(source) {
return builder.image(source)
}Use it in your component:
import { urlFor } from '@/lib/sanityImageUrl'
function MyComponent({ image }) {
return (
<img
src={urlFor(image).width(800).url()}
alt={image.alt || ''}
/>
)
}3. Important: Pass the whole image object, not just the reference
Make sure you're passing the entire image object to urlFor(), not just image.asset._ref. The builder needs the full object including crop and hotspot data.
Why file.asset._ref doesn't work
The _ref field contains something like image-abc123-800x600-jpg which is an internal Sanity reference, not a URL. You need to either:
- Resolve it in your query with
->url - Use
@sanity/image-urlto build the URL - Manually construct the URL using the Sanity CDN format
The @sanity/image-url approach is recommended because it handles all the complexity for you, including transformations, crops, and hotspots.
Show original thread3 replies
Was this answer helpful?
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.