Using locally scoped variables for objects and documents in Sanity schema files.
Great question! There are actually two main ways to handle this without constantly updating that giant schemaTypes array:
1. Inline Object Types (Best for Single-Use Objects)
You can define object types directly inline within fields without adding them to the schemaTypes array. This is perfect for objects you'll only use in one place:
// In your document schema file
export const blogPost = defineType({
name: 'blogPost',
type: 'document',
fields: [
defineField({
name: 'author',
type: 'object', // Inline object - no schemaTypes entry needed!
fields: [
{ name: 'name', type: 'string' },
{ name: 'bio', type: 'text' }
]
}),
defineField({
name: 'relatedPosts',
type: 'array',
of: [
defineArrayMember({
type: 'object', // Another inline object
name: 'relatedPost',
fields: [
{ name: 'title', type: 'string' },
{ name: 'url', type: 'url' }
]
})
]
})
]
})These inline objects work immediately without touching your config file. They're scoped to that specific field, so you can't reuse them elsewhere, but that's often exactly what you want.
2. Auto-Import with import.meta.glob (Best for Organization)
For a cleaner setup where you want to reuse types, you can use import.meta.glob to automatically collect all schema files:
// schemas/index.ts
import { defineType } from 'sanity'
// Automatically import all schema files
const schemaFiles = import.meta.glob('./**/*.ts', { eager: true })
export const schemaTypes = Object.values(schemaFiles)
.map((module: any) => module.default)
.filter(Boolean)
// sanity.config.ts
import { defineConfig } from 'sanity'
import { schemaTypes } from './schemas'
export default defineConfig({
// ...
schema: {
types: schemaTypes
}
})Now you can create new schema files in your schemas/ directory and they'll automatically be included. No more manual array updates!
The Short Answer
For the specific scenario you described (creating a document type and using it in the same file), you have two options:
- If it's reusable: Define it as a separate
defineType()in the same file and export both types, then add both to schemaTypes once - If it's single-use: Use an inline object type (shown above) - no schemaTypes entry needed at all
Sanity does need to know about top-level document and object types (the ones in schemaTypes), but inline objects within fields are compiled on-the-fly and work immediately. The import.meta.glob approach just makes managing that top-level array less painful as your schema grows.
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.