Assign an aspect to an asset
Assign aspects to an asset programmatically.
This guide explores options for programmatically assigning aspects to Media Library assets.
Prerequisites:
mediaLibraryId: The ID for your organization's Media Library.- Read/write access to documents in Media Library.
- A personal authentication token, or an organization-wide robot token with read/write access to Media Library.
Mutate the asset
To add an aspect to an asset, you need to mutate the asset in Media Library. Rather than capture and rewrite the whole asset, use a patch to apply only the aspect change to the asset document.
Set aspects with the Sanity CLI
Use the media import CLI command to set aspects on a single asset or a set of assets. For more information, see importing assets. If the asset already has a value for that aspect, media import skips it. Pass --replace-aspects to overwrite existing aspect data.
Pro tip
This option requires that you have a local copy of the file you're adding aspect information for. Use media export to generate an archive of the assets in your library alongside their existing aspect data.
Set aspects with the HTTP API
Use the media-libraries/<media-library-id>/mutate endpoint to apply the mutation.
This example patches the value of a single-field aspect named comment.
const mediaLibraryId = 'MEDIA_LIBRARY_ID'
const ASSET_ID = 'ASSET_ID'
const url = `https://api.sanity.io/v2025-02-19/media-libraries/${mediaLibraryId}/mutate`
const mutation = JSON.stringify({
mutations: [
{
patch: {
id: ASSET_ID,
setIfMissing: { aspects: {} }, // confirm the asset has an aspects property.
set: {
"aspects.comment": "Updated aspect details"
}
}
}
]
})
await fetch(url, {
method: 'POST',
headers: {
"Content-type": "application/json",
"Authorization": `Bearer ${process.env.SANITY_API_TOKEN}`
},
body: mutation
})This modifies the asset document to look something like this:
{
"title": "myImage.jpg",
"assetType": "sanity.imageAsset",
"_rev": "8397ffea-abf2-4eed-b6b7-d5e383171061",
"_type": "sanity.asset",
"aspects": {
"comment": "Updated aspect details"
},
"_createdAt": "2025-04-02T15:46:26Z"
}For nested fields or more complex aspects, start with the outermost name and work down to the individual field level.
Set aspects with the @sanity/client library
Configure your client with a Media Library resource, then use client.patch() to assign aspect values to an asset:
import {createClient} from '@sanity/client'
const client = createClient({
apiVersion: '2026-03-01',
useCdn: false,
token: process.env.SANITY_API_TOKEN,
resource: {
type: 'media-library',
id: 'MEDIA_LIBRARY_ID',
},
})
// Assign an aspect value to an asset
await client
.patch('ASSET_ID')
.setIfMissing({aspects: {}})
.set({'aspects.comment': 'Updated aspect details'})
.commit()