DOMParser is not defined error with @sanity/block-tools in sanity exec

6 replies
Last updated: Nov 29, 2025
Hi again! Ive been trying to use
@sanity/block-tools
and i keep getting this error:
ReferenceError: DOMParser is not defined
    at defaultParseHtml (***/studio/node_modules/@sanity/block-tools/lib/HtmlDeserializer/helpers.js:173:35)
Happens on my own code as well as the example code provided in the packages readme, here:
https://github.com/sanity-io/sanity/blob/next/packages/%40sanity/block-tools/README.md I am running the script through
sanity exec
Im puzzled
😭
AI Update

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 jsdom

Then, 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 thread
6 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.

Was this answer helpful?