Discussion on using code input for <BlockContent> frontend and transitioning to Next.js with Sanity
To add code input support to your Sanity project and render it on the frontend, you'll need to set up both the Studio configuration and the frontend rendering. Here's how:
Studio Setup
First, install the @sanity/code-input plugin:
npm i @sanity/code-inputThen add it to your sanity.config.ts:
import {defineConfig} from 'sanity'
import {codeInput} from '@sanity/code-input'
export default defineConfig({
// ... other config
plugins: [
codeInput(),
// ... other plugins
]
})Schema Configuration
Add the code type to your schema, typically within a Portable Text array:
{
name: 'content',
title: 'Content',
type: 'array',
of: [
{type: 'block'},
{
type: 'code',
options: {
withFilename: true, // Allow adding filenames
highlightedLines: true, // Enable line highlighting
languageAlternatives: [ // Optional: restrict languages
{title: 'JavaScript', value: 'javascript'},
{title: 'TypeScript', value: 'typescript'},
{title: 'Python', value: 'python'}
]
}
}
]
}Frontend Rendering with @portabletext/react
For rendering on the frontend with @portabletext/react, you need to create a custom serializer for the code type:
import {PortableText} from '@portabletext/react'
const components = {
types: {
code: ({value}) => (
<pre data-language={value.language}>
<code>{value.code}</code>
</pre>
)
}
}
// In your component
<PortableText value={content} components={components} />For a more feature-rich implementation with syntax highlighting, you can use libraries like Prism or Highlight.js:
import Refractor from 'react-refractor'
import javascript from 'refractor/lang/javascript'
Refractor.registerLanguage(javascript)
const components = {
types: {
code: ({value}) => (
<div>
{value.filename && <div className="filename">{value.filename}</div>}
<Refractor
language={value.language || 'text'}
value={value.code}
/>
</div>
)
}
}Code Block Data Structure
The code input data structure includes:
code: The actual code stringlanguage: The programming language identifierfilename: Optional filename (if enabled withwithFilename)highlightedLines: Optional array of line numbers to highlight (if enabled)
This gives you a fully functional code input experience in Sanity Studio with proper rendering on your frontend! The Code Input plugin documentation has additional details if you need more advanced configurations.
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.