Adding HTML to a document in Sanity using client.create() function and HTML to Portable Text Field plugin.
While Sanity doesn't have specific documentation about adding HTML directly to documents via client.create(), the recommended approach is to convert HTML to Portable Text format first using the @sanity/block-tools package.
Converting HTML to Portable Text
When you need to add HTML content to a Sanity document, you should:
- Install the required packages:
npm install @sanity/block-tools jsdom- Convert HTML to Portable Text blocks using
htmlToBlocks():
const {htmlToBlocks} = require('@sanity/block-tools')
const {JSDOM} = require('jsdom')
const html = '<p>Your HTML content here</p>'
const blocks = htmlToBlocks(html, blockContentType, {
parseHtml: (html) => new JSDOM(html).window.document
})- Create the document with converted content:
const doc = {
_type: 'yourDocumentType',
title: 'Document Title',
body: blocks // Your converted Portable Text
}
client.create(doc).then((res) => {
console.log(`Document created with ID: ${res._id}`)
})Why Portable Text Instead of HTML?
Sanity uses Portable Text as its structured content format rather than raw HTML. This provides several benefits:
- Presentation-agnostic: Content can be rendered across different platforms (web, mobile, etc.)
- Structured and queryable: You can query and manipulate content programmatically
- Future-proof: Content isn't tied to HTML rendering
About client.create()
The client.create() method expects a plain JavaScript object representing the document. It must contain a _type attribute and may optionally contain an _id. For rich text content fields, that content should be in Portable Text format rather than raw HTML.
const doc = {
_type: 'bike',
name: 'Sanity Tandem Extraordinaire',
seats: 2,
}
client.create(doc).then((res) => {
console.log(`Bike was created, document ID is ${res._id}`)
})Resources for HTML to Portable Text Conversion
- @sanity/block-tools documentation - Complete guide on HTML to Portable Text conversion
- Converting HTML to Portable Text tutorial - Step-by-step migration guide
- Custom deserialization rules - For handling complex HTML structures and inline styles
- JavaScript Client on GitHub - Official client repository with full API documentation
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.