How to populate a Sanity schema with read-only data?
Yes, you can populate a schema with read-only data in Sanity! There are several approaches depending on your use case:
Using the readOnly Property
The simplest way is to use the readOnly property on your field definitions. This makes fields visible but not editable:
{
name: 'generatedId',
type: 'string',
readOnly: true
}Conditional Read-Only Fields
You can also make fields read-only based on conditions using callback functions, as explained in the Conditional Fields documentation:
{
name: 'publishedDate',
type: 'datetime',
readOnly: ({document}) => document?.status === 'published'
}The callback receives parameters like parent, document, value, and currentUser, allowing you to create dynamic read-only logic.
Populating Read-Only Data
To actually populate these read-only fields with data, you have a few options:
- Initial values - Set default values when documents are created:
{
name: 'createdAt',
type: 'datetime',
readOnly: true,
initialValue: () => new Date().toISOString()
}Document actions - Use custom document actions to programmatically set values before saving
Mutations via API - Populate data through the Sanity API (mutations can write to read-only fields - the read-only restriction only applies to the Studio UI)
Sanity Functions - Use Sanity Functions to automatically populate fields when documents are created or updated through event handlers
The key thing to remember is that readOnly only affects the Studio editing interface - it doesn't prevent programmatic updates via the API. This gives you flexibility to populate data through automated processes while preventing manual editing by content creators.
Show original thread8 replies
Was this answer helpful?
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.