Code formatting plugin for Sanity block content
Yes! There's an official plugin called @sanity/code-input that adds code formatting capabilities to Sanity Studio, similar to what you see in Slack's code blocks.
Installation
npm i @sanity/code-inputSetup
After installing, add it to your schema as a custom block type within your Portable Text array:
defineField({
name: 'body',
type: 'array',
of: [
{ type: 'block' },
{
type: 'code',
options: {
withFilename: true, // Allow adding filename to code blocks
highlightedLines: true // Enable line highlighting
}
}
]
})This gives your content editors a syntax-highlighted code editor right in the Studio where they can paste and format code snippets.
Rendering on the Frontend
When rendering the code blocks on your website, you'll need to handle the code type in your Portable Text serializers. Here's an example for React:
const components = {
types: {
code: ({value}) => (
<pre data-language={value.language}>
<code>{value.code}</code>
</pre>
)
}
}The plugin stores the code as structured data with properties like language and code, so you can enhance the rendering with any syntax highlighting library you prefer (like Prism.js or Highlight.js).
The @sanity/code-input plugin is maintained by the Sanity team and is widely used in the community for technical blogs, documentation sites, and any content that needs to display code snippets with proper formatting.
Show original thread22 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.