
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeTo 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:
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
]
})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'}
]
}
}
]
}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>
)
}
}The code input data structure includes:
code: The actual code stringlanguage: The programming language identifierfilename: Optional filename (if enabled with withFilename)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 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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store