Sanity editors pasting from Word or Google Docs: clean up broken Portable Text

By Nayan Kyada · · 6 min read

Part of The Sanity + Next.js Guide

If your editors write in Word or Google Docs and paste into Sanity, you have probably seen it: a random gap in the middle of an article, a heading that looks wrong, a list that renders as plain text. This is broken Portable Text from pasted content, and it is one of the most common reasons editors lose trust in a Sanity site. It is fixable, and mostly in the schema and the renderer rather than in the editors' habits.

What pasted content does to Portable Text

Portable Text is structured data, not HTML. When someone pastes rich text, Studio tries to map each piece onto your schema: paragraphs become blocks, bold becomes a mark, headings become styles. Anything that does not map cleanly still gets stored, and that is where problems start.

The symptoms I see on inherited sites:

  • Large vertical gaps caused by empty blocks, usually from blank lines in the source document.
  • Heading levels that skip, for example an h4 under an h2, because the source used styles your design never expected.
  • Lists that lose their nesting or turn into paragraphs starting with a dash character.
  • Links with tracking redirect URLs, such as the ones Google Docs sometimes wraps links in.
  • Whole sections silently missing on the live site because the frontend does not know a style or mark name.

None of these throw an error. That is why they sit in production for months.

What it costs to ignore

The visible cost is editors who spend twenty minutes per article fixing formatting by hand, then stop using Studio for anything beyond typos. The less visible cost is SEO: skipped heading levels and empty elements weaken page structure, and long runs of empty blocks hurt readability and layout stability. If you also see editors working around the Studio in other ways, read my notes on why editors avoid Sanity Studio and the fix.

Step 1: measure how bad it is

Before changing anything, count the damage. This GROQ query finds documents containing empty text blocks:

*[_type == "post" && count(body[_type == "block" && length(pt::text(@)) == 0]) > 0]{
  _id,
  title,
  "emptyBlocks": count(body[_type == "block" && length(pt::text(@)) == 0])
} | order(emptyBlocks desc)

Run it in Vision, the query tool inside Studio. Swap the document type and field name for your own. You can build similar queries for unexpected styles by comparing each block's style against the list you actually support. If your queries get more involved, my guide to advanced GROQ queries covers the patterns.

Step 2: restrict the schema so bad structure has nowhere to land

Most rescued schemas I open have a block type with every default style and decorator enabled, plus a dozen custom blocks nobody uses. Trim it to what the design really renders. Fewer allowed styles means pasted headings get normalised instead of stored as something your frontend cannot style.

// sanity/schemaTypes/blockContent.ts
import {defineType, defineArrayMember} from 'sanity'
 
export const blockContent = defineType({
  name: 'blockContent',
  title: 'Body',
  type: 'array',
  of: [
    defineArrayMember({
      type: 'block',
      styles: [
        {title: 'Paragraph', value: 'normal'},
        {title: 'Heading 2', value: 'h2'},
        {title: 'Heading 3', value: 'h3'},
        {title: 'Quote', value: 'blockquote'},
      ],
      lists: [
        {title: 'Bullet', value: 'bullet'},
        {title: 'Numbered', value: 'number'},
      ],
      marks: {
        decorators: [
          {title: 'Strong', value: 'strong'},
          {title: 'Emphasis', value: 'em'},
        ],
        annotations: [
          {
            name: 'link',
            type: 'object',
            title: 'Link',
            fields: [{name: 'href', type: 'url', title: 'URL'}],
          },
        ],
      },
    }),
    defineArrayMember({type: 'image'}),
  ],
})

The rule I follow: if the design system has no style for it, the schema does not offer it. Studio then maps unsupported source formatting onto the closest allowed style instead of preserving something your site cannot render. Test with a real document from your editors rather than a clean sample, because that is where the surprises are.

If this schema has also grown into a sprawl of block types, the same logic applies at page level; see rescuing an out-of-control page builder.

Step 3: make the frontend fail loudly in development

Silent failure is what let this hide. The Portable Text renderer for React lets you define handlers for unknown types, marks, block styles and lists. Use them to log in development and render a safe fallback in production, so a stray style produces a paragraph rather than a hole. I would not show editors a visible error banner on the live site, but a console warning plus a preview-only highlight makes problems obvious during review. Component patterns are in my write-up on Portable Text custom components in Next.js.

Step 4: clean existing content with a migration script

Schema changes do not rewrite old documents. For the backlog, use a script that removes empty blocks and normalises styles. Always run it against a copy of the dataset first, as the content is the asset you cannot rebuild.

// scripts/clean-empty-blocks.ts
import {createClient} from '@sanity/client'
 
const client = createClient({
  projectId: process.env.SANITY_PROJECT_ID!,
  dataset: process.env.SANITY_DATASET!,
  apiVersion: '2025-01-01',
  token: process.env.SANITY_WRITE_TOKEN!,
  useCdn: false,
})
 
type Span = {text?: string}
type Block = {_type: string; children?: Span[]; style?: string}
 
const isEmptyBlock = (b: Block) =>
  b._type === 'block' &&
  (b.children ?? []).every((c) => !(c.text ?? '').trim())
 
async function run() {
  const docs = await client.fetch<{_id: string; body: Block[]}[]>(
    `*[_type == "post" && defined(body)]{_id, body}`
  )
  for (const doc of docs) {
    const cleaned = doc.body.filter((b) => !isEmptyBlock(b))
    if (cleaned.length === doc.body.length) continue
    await client.patch(doc._id).set({body: cleaned}).commit()
    console.log('Cleaned', doc._id)
  }
}
 
run()

Two cautions. First, this patches published documents directly, so check whether drafts exist and handle them too, or editors will overwrite your fix when they publish. Second, keep the write token out of the repo and revoke it afterwards. Exposed tokens are a separate problem; I cover that in checking for an exposed Sanity API token.

Step 5: give editors a short paste routine

Technical fixes handle most cases, but a one-page guide helps: paste as plain text for body copy, apply styles inside Studio, and add images through the image block rather than pasting them. This is the kind of setup work covered in what to configure before editors touch a CMS.

How to verify the fix

  • The GROQ query from step 1 returns zero documents.
  • A real pasted Google Docs article renders with correct heading order and no gaps.
  • No unknown style or mark warnings appear in the development console on your five longest articles.
  • Editors confirm that publishing from a pasted draft no longer needs manual cleanup.

What to ask a developer

Ask how they will measure the damage first, whether they test with real editor content, whether the migration runs on a dataset copy, and how drafts are handled. A developer who only proposes tightening the schema will leave old content broken. One who only writes a script will let the mess return.

This is work I do as part of a Performance and Sanity audit, from $800, which covers the schema, the renderer and a content cleanup plan for your site.

Frequently asked questions

Why does pasting from Google Docs break my Sanity content?

Pasted text carries structure the schema was never designed for, such as extra heading levels, empty paragraphs, odd lists and inline images. Studio converts what it can into Portable Text blocks, and anything your frontend does not recognise renders as nothing or as a fallback.

How do I find empty blocks in Sanity Portable Text?

Run a GROQ query that filters body blocks where the plain text length is zero, using the pt::text function. It returns every document with at least one empty block so you can fix them in bulk.

Can I stop editors pasting bad formatting into Sanity?

You can limit what survives a paste by restricting styles, marks, lists and block types in the schema, because unsupported formatting has nowhere to land. Pair that with a short editor guide and a fallback renderer on the frontend.