How to get image URL from asset._ref in Sanity?
To get the image URL from an asset._ref in Sanity, you need to dereference the asset in your GROQ query. Here's how:
Quick Solution
In your GROQ query, use the -> operator to dereference the asset and access its url property:
*[_type == 'yourDocumentType'] {
title,
"images": images[]{
"url": asset->url,
alt
}
}The key part is asset->url - the -> operator follows the reference to the actual asset document and retrieves the URL.
Full Example for a Carousel
If you have an array of images and want to display them in a carousel:
*[_type == 'carousel'][0] {
title,
"images": images[]{
"url": asset->url,
alt,
// Optional: get additional metadata
"width": asset->metadata.dimensions.width,
"height": asset->metadata.dimensions.height
}
}This will give you a result like:
{
"title": "My Carousel",
"images": [
{
"url": "https://cdn.sanity.io/images/project-id/dataset/image-id-300x450.jpg",
"alt": "Image description"
}
]
}Using the URL in Your Frontend
Once you have the URL, you can use it directly in your carousel component:
images.map((image) => (
<img
key={image.url}
src={image.url}
alt={image.alt || ''}
/>
))Better Approach: Use @sanity/image-url
For more control over image transformations (resizing, cropping, format optimization), I recommend using the @sanity/image-url package instead:
import { createImageUrlBuilder } from '@sanity/image-url'
import { client } from './sanityClient'
const builder = createImageUrlBuilder(client)
function urlFor(source) {
return builder.image(source)
}
// In your component
images.map((image) => (
<img
src={urlFor(image)
.width(800)
.height(600)
.url()}
alt={image.alt || ''}
/>
))This approach automatically respects crop and hotspot settings and lets you optimize images on-the-fly.
Show original thread4 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.