Adding Image Caption and Attribution to API.js
Great question! After adding those custom fields to your image schema, you need to update your frontend queries and components to fetch and display that data. Here's what you need to do:
1. Update Your GROQ Query
First, modify your query to include the caption and attribution fields. When querying the post, expand the mainImage field to include its custom fields:
const query = `*[_type == "post" && slug.current == $slug][0]{
title,
body,
mainImage {
asset->{
_id,
url
},
caption,
attribution,
hotspot,
crop
}
}`The key here is that caption and attribution are stored at the same level as asset, hotspot, and crop within the image object, not inside the asset itself.
2. Display the Data in Your Component
Once you have the data, you can render it in your frontend component. Here's an example using React:
import Image from 'next/image'
import { urlFor } from '@/lib/sanity'
function PostImage({ mainImage }) {
if (!mainImage?.asset) return null
return (
<figure>
<Image
src={urlFor(mainImage).url()}
alt={mainImage.caption || 'Post image'}
width={800}
height={600}
/>
{mainImage.caption && (
<figcaption>{mainImage.caption}</figcaption>
)}
{mainImage.attribution && (
<cite>{mainImage.attribution}</cite>
)}
</figure>
)
}3. Build the Image URL
If you're using the Sanity image URL builder, make sure it's set up in your project:
import imageUrlBuilder from '@sanity/image-url'
import { client } from './sanity'
const builder = imageUrlBuilder(client)
export function urlFor(source) {
return builder.image(source)
}The important thing to remember is that custom fields like caption and attribution live on the image field itself (alongside asset, crop, and hotspot), not inside the asset document. So when you query, you access them as mainImage.caption and mainImage.attribution, not mainImage.asset.caption.
This pattern is documented in the Image Type documentation and is particularly useful for storing accessibility information and attribution that's specific to how an image is used in a particular document, rather than metadata that belongs to the asset itself.
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.