initialValue not working for string field in existing Sanity document
initialValueof a string input, following the official Sanity documentation . I copied one of the examples and it doesn't seem to be working in my studio (I'm expecting the value of
InitialValueto appear in the text input field). To provide additional context, I'm trying to add this field to an existing document, maybe that what's causing the issue.
Please let me know if there's anything I'm doing wrong and thank you in advance.
schema:
export default {
name: 'info',
title: 'Information',
type: 'document',
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
initialValue: 'Hello World',
},
],
}export default {
name: 'info',
title: 'Information',
type: 'document',
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
},
],
initialValue: {
title: 'Hello World',
},
}Your schema looks correct, but there's an important detail about how initialValue works in Sanity: it only applies when creating new documents, not to existing ones.
Both of your approaches are valid syntax:
// Field-level initialValue
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
initialValue: 'Hello World',
},
]
// Document-level initialValue
initialValue: {
title: 'Hello World',
}However, if you're testing this on a document that already exists (even if the title field is empty), the initialValue won't populate. This is by design - as explained in the Initial Value Templates documentation, initialValue only sets values when you first create a brand new document.
To test if it's working:
- Go to your Studio
- Create a completely new "Information" document (not editing an existing one)
- You should see "Hello World" pre-populated in the title field
If you need to set values on existing documents:
You'll need to use a migration script with the @sanity/client. Here's an example:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'your-dataset',
token: 'your-token-with-write-access',
apiVersion: '2024-01-01',
})
client
.patch({query: '*[_type == "info" && !defined(title)]'})
.set({title: 'Hello World'})
.commit()
.then(() => console.log('Done!'))This would update all existing "info" documents that don't have a title yet.
The key takeaway: initialValue is for new document creation only, not for backfilling existing documents. If your field is showing up empty on existing documents, that's expected behavior!
Show original thread2 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.