How to Insert an Image into a Portable Text Block with Alt Text and Caption Predefined
Yes, it is possible to configure an image object in Sanity Studio so editors can insert images into portable text with predefined alt text and captions! Here's how this works:
Adding Custom Fields to Images
You can add custom fields like alt and caption directly to your image schema within the portable text block definition:
import {defineField, defineArrayMember} from 'sanity'
defineField({
name: 'body',
title: 'Body',
type: 'array',
of: [
{type: 'block'},
defineArrayMember({
type: 'image',
options: {
hotspot: true
},
fields: [
{
name: 'alt',
title: 'Alt Text',
type: 'string',
description: 'Important for SEO and accessibility'
},
{
name: 'caption',
title: 'Caption',
type: 'string'
}
]
})
]
})About Asset-Level Metadata
While Sanity's image asset documents store metadata like dimensions and color palette automatically, image assets themselves don't have built-in altText or caption fields. These fields need to be defined at the document level (as shown above).
Creating Inline Images
For truly inline images (appearing within the text flow rather than as separate blocks), you can create custom inline objects using the of property within your block definition:
defineArrayMember({
type: 'block',
of: [
{
type: 'image',
name: 'inlineImage',
title: 'Inline Image',
options: {inline: true},
fields: [
{name: 'alt', type: 'string', title: 'Alt Text'},
{name: 'caption', type: 'string', title: 'Caption'}
]
}
]
})The Inheritance Challenge
Your ideal scenarioāsetting alt text and caption when an image is first uploaded, then allowing overrides in subsequent usesāis not directly supported in Sanity's architecture. Here's why:
- Image assets are stored separately from the documents that reference them
- Each time you add an image to a document, you're creating a new reference with its own field values
- There's no automatic inheritance from asset-level metadata to document-level fields
Workaround Options
Use a media plugin like sanity-plugin-media to add custom metadata fields to your assets at upload time, though you'd still need to manually copy these values when inserting images
Create a custom input component that automatically populates alt/caption fields from asset metadata (if you've stored it there) but allows editors to override it
Use initial value templates to provide default values for these fields when images are added
The fields-on-image approach shown above is the standard pattern and gives you the flexibility you need, though it requires editors to fill in these fields each time they use an image.
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.