DOMParser is not defined error with @sanity/block-tools in sanity exec
The error you're seeing happens because @sanity/block-tools needs a DOM parser to work, but Node.js doesn't have one built-in (DOMParser is a browser API). When you run code through sanity exec, you're in a Node.js environment, not a browser.
The fix is to provide a custom parseHtml function using a library like jsdom that implements DOM APIs in Node.js.
First, install jsdom:
npm install jsdomThen, when using htmlToBlocks, pass a custom parseHtml function in the options:
import { htmlToBlocks } from '@sanity/block-tools';
import { JSDOM } from 'jsdom';
// Create a parseHtml function using jsdom
const parseHtml = (html) => {
return new JSDOM(html).window.document;
};
// Use it in your conversion
const blocks = htmlToBlocks(
'<p>Your HTML here</p>',
blockContentType, // your block type schema
{
parseHtml: parseHtml, // Pass the custom parser
}
);The parseHtml option tells @sanity/block-tools to use jsdom's DOMParser instead of the browser's built-in one. This is mentioned in the migration course on converting HTML to Portable Text where they show using jsdom for Node.js environments.
Without this option, the library tries to use the default browser DOMParser, which doesn't exist in Node.js - hence your error at defaultParseHtml in the helpers.js file.
This pattern works for any Node.js script, including those run with sanity exec! đ
Show original thread6 replies
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.