
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeI understand what you're trying to do, but unfortunately Sanity schemas must be static and cannot be dynamically generated at runtime based on data. The fields array in a schema definition needs to be defined when the Studio is built/loaded, not dynamically created per document.
Here's why and what alternatives you have:
Sanity Studio needs to know the complete schema structure upfront to:
You're correct that initialValue only sets the values of existing fields - it doesn't create new fields. And while references link to other documents, they don't dynamically alter the schema structure itself.
Depending on what you're trying to accomplish, here are some solutions:
If you need fields to appear/disappear based on document data, use the hidden property:
defineField({
name: 'conditionalField',
type: 'string',
hidden: ({document}) => document?.someField !== 'specificValue'
})For truly dynamic data structures, use an array of objects where users can add different field combinations:
defineField({
name: 'dynamicContent',
type: 'array',
of: [
{type: 'textBlock'},
{type: 'imageBlock'},
{type: 'customBlock'}
]
})While you can't create fields dynamically, you can use Initial Value Templates to fetch data from other documents and populate field values when creating new documents:
{
id: 'document-from-template',
title: 'New Document',
schemaType: 'myType',
value: async (params, context) => {
const client = context.getClient({apiVersion: '2024-11-01'})
const sourceData = await client.fetch(
`*[_type == "source" && _id == $id][0]`,
{id: params.sourceId}
)
return {
field1: sourceData.someValue,
field2: sourceData.anotherValue
// These fields must already exist in your schema
}
}
}For truly arbitrary data, use an array of key-value pairs:
defineField({
name: 'metadata',
type: 'array',
of: [{
type: 'object',
fields: [
{name: 'key', type: 'string'},
{name: 'value', type: 'string'}
]
}]
})If you need completely different field sets, create separate document types and use Initial Value Templates to guide users to the right one based on context.
If you can share more about your specific use case (what kind of data you're trying to pull and why you need it to generate fields), I can suggest a more tailored approach!
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