How come images are returning with just a _ref in their assets?

9 replies
Last updated: Feb 3, 2021
How come images are returning with just a _ref in their assets?
AI Update

This is actually expected behavior! When you query images in Sanity, they come back as references by default because images in Sanity are stored as separate asset documents in the Content Lake, and your document just holds a reference to that asset.

The structure typically looks like this:

{
  "image": {
    "asset": {
      "_ref": "image-abc123...",
      "_type": "reference"
    }
  }
}

To get the actual image data (URL, dimensions, metadata, etc.), you need to dereference the asset in your GROQ query. Here's how:

Basic dereferencing:

*[_type == "yourDocType"] {
  image {
    asset->
  }
}

The -> operator follows the reference and returns the full asset document.

Getting specific image fields:

*[_type == "yourDocType"] {
  image {
    asset->{
      url,
      metadata {
        dimensions
      }
    }
  }
}

Including custom fields and metadata: If you've added custom fields to your image type (like alt text), you can include those too:

*[_type == "yourDocType"] {
  image {
    asset->{
      url,
      metadata
    },
    alt,
    hotspot,
    crop
  }
}

This architecture of storing images as separate asset documents with references is actually a powerful feature - it allows Sanity to:

  • Reuse the same image across multiple documents without duplication
  • Manage assets independently with their own metadata
  • Provide efficient asset management through the Content Lake

You can read more about how the Image Type works in Sanity's documentation, including how to configure metadata, hotspot, and custom fields. The docs also have a great guide on displaying images that covers querying and rendering them on the frontend.

This is a reference to the asset in sanity. If you use the url builder, this asset object is all it needs to provide you with the image URL.
I need the url for the image because I’m trying to pass it as a backgroundImage in css, hopefully… if not the ref is fine I suppose
But the component im working on cant use an Img tag as a background I dont think
The URL builder will take the ref and give you the image url
ok
I dont get why I’m getting onyl a ref for this particular image but never for others one.
Hell yeah, it worked thanks
Ollie Taylor
No worries, glad I could help!

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?