Setting initial values for reference fields in Sanity schema.
Yes, absolutely! You can set initial values for reference fields in Sanity. There are two main approaches depending on your needs:
1. Field-Level Initial Value (Simple)
For a straightforward default reference that applies every time a document is created, add initialValue directly to your schema field:
defineField({
name: 'author',
type: 'reference',
to: [{type: 'author'}],
initialValue: {
_type: 'reference',
_ref: 'your-default-author-id-here'
}
})This will pre-populate the author field with the specified reference whenever someone creates a new post.
2. Initial Value Templates (Dynamic/Contextual)
For more sophisticated scenarios—like automatically setting the author to the current user—use Initial Value Templates in your sanity.config.ts:
// sanity.config.ts
export default defineConfig({
// ... other config
document: {
newDocumentOptions: (prev, context) => {
return [
...prev,
{
id: 'post-with-author',
title: 'Post',
schemaType: 'post',
value: async (params, context) => {
// Get current user
const {id} = context.currentUser
// Find corresponding author document
const client = context.getClient({apiVersion: '2024-11-01'})
const author = await client.fetch(
`*[_type == "author" && userId == $userId][0]._id`,
{userId: id}
)
return {
author: {
_type: 'reference',
_ref: author
}
}
}
}
]
}
}
})This approach lets you:
- Set the author based on who's logged in
- Pass parameters to customize the initial value
- Fetch data from your content lake or external APIs
- Create multiple document creation options for the same type
The template-based approach is particularly powerful when combined with the Structure Builder for creating contextual workflows, like automatically linking child documents to their parent.
Both methods work great—use field-level initialValue for static defaults, and Initial Value Templates when you need dynamic or user-specific values!
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.