How to get image URL from asset._ref in Sanity?

4 replies
Last updated: Feb 25, 2022
Im trying to post the images from the array in a carousel, but i cant get hold of the image url inside asset.ref?? any clue what to do?
AI Update

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.

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 thread
4 replies
You need a projection in your groq query: https://www.sanity.io/docs/presenting-images#BnS1mFRw
It's confusing when you first encounter it but, inside of a document an image field is actually a reference to an asset in your Content Lake. When you're querying for it, you need to expand that asset. For example:
<image-field> {
  ...,
  asset->
}
right! fixed it πŸ˜„
right! fixed it πŸ˜„

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?