Portable Text "Unknown block type 'code'" despite adding serializer

9 replies
Last updated: Nov 29, 2025
Hello all! I’m trying to render a code block in a Portable Text Block, followed the instructions to add the serializer and still gives me the Unknown block type “code”, please specify a serializer for it in the
serializers.types
prop
import BlockContent from '@sanity/block-content-to-react'
const CodeRenderer = props => {
    console.log('Render code block: ', props)
    return BlockContent.defaultSerializers.types.block(props)
}

...

<BlockContent
   blocks={post._rawExcerpt}
   serializers={{
       types: {
           code: CodeRenderer
       }
   }}
/>
AI Update

I see the issue! Your CodeRenderer component is calling BlockContent.defaultSerializers.types.block(props), which is actually rendering it as a regular text block instead of a code block. This is why you're still getting the error.

Here's what you need to fix:

import BlockContent from '@sanity/block-content-to-react'

const CodeRenderer = props => {
    console.log('Render code block: ', props)
    return (
        <pre>
            <code>{props.node.code}</code>
        </pre>
    )
}

<BlockContent
   blocks={post._rawExcerpt}
   serializers={{
       types: {
           code: CodeRenderer
       }
   }}
/>

The key points:

  1. Access the code content via props.node.code (not by calling the default block serializer)
  2. Return actual code markup - typically a <pre><code> combination
  3. If your schema includes a language field, you can access it via props.node.language for syntax highlighting

If you want to add syntax highlighting, you could use something like:

import SyntaxHighlighter from 'react-syntax-highlighter'

const CodeRenderer = props => {
    return (
        <SyntaxHighlighter language={props.node.language || 'text'}>
            {props.node.code}
        </SyntaxHighlighter>
    )
}

Important note: The @sanity/block-content-to-react package is deprecated. For new projects, you should use @portabletext/react instead. The migration is straightforward - the main difference is using a components prop instead of serializers, and accessing value instead of node:

import {PortableText} from '@portabletext/react'

const components = {
    types: {
        code: ({value}) => (
            <pre>
                <code>{value.code}</code>
            </pre>
        )
    }
}

<PortableText value={post._rawExcerpt} components={components} />
Show original thread
9 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?