Importing block content with images into Sanity and resolving issues.
Great question! When importing block content with images using @sanity/block-tools, you'll need to set up your deserialize rules to handle image elements and use the _sanityAsset helper to tell Sanity to fetch and import those images during the import process.
Here's the key pattern that works well:
'rules': [
{
deserialize(el, next, block) {
if (el.tagName?.toLowerCase() === 'img') {
return block({
_type: 'image',
_sanityAsset: `image@${el.src}`,
nodes: next(el.childNodes),
})
}
}
}
]The magic happens with _sanityAsset: 'image@${el.src}' - this tells Sanity's import process to fetch the image from the URL in el.src and create a proper Sanity asset during import.
Complete workflow
Your block content schema should look something like this:
{
type: 'array',
name: 'content',
title: 'Content',
of: [
{
type: 'block',
},
{
type: 'image',
fields: [
{
type: 'string',
name: 'alt',
title: 'Alt',
description: 'The alt text of the image',
},
],
},
],
}Then when querying the content, you can access the imported images like this:
content[] {
...,
_type == "image" => {
"src": asset->url,
alt,
},
}Important notes
No pre-loading needed: You don't need to upload the images to Sanity beforehand. The
_sanityAssethelper fetches and imports them automatically during the import process.URL accessibility: Make sure the image URLs in your source content are publicly accessible when you run the import.
NDJSON output: Your import script should output to an NDJSON file, which you then import using the Sanity CLI:
sanity dataset import your-file.ndjson production
The _sanityAsset helper works with the format image@<url> for images and file@<url> for other file types, making it straightforward to import various asset types into your Sanity dataset.
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.