How to render Sanity images in Next.js using file.asset._ref?

3 replies
Last updated: Oct 3, 2023
I try to render the image from sanity media in nextjs by using
file.asset._ref
but 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?
AI Update

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.

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-url

Set 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-url to 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 thread
3 replies
Hello Alex,
in your groc queries you can do this :
"image": image.asset-&gt;{url, altText}

and then in your component you can do this :
image.url

(sorry for the backticks i’m on my phone)
Nice is working! thank you I'll handle it from here.
Let’s go 🥳

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?