GraphQL - Error: Encountered anonymous inline image
When you add a fields array to an image type in your Sanity schema, you're creating what's called an "anonymous inline object type." While this works in Sanity Studio, GraphQL requires all object types to have explicit names to properly generate its schema.
The error you're seeing is because GraphQL can't work with unnamed inline objects. The solution is to "lift" your image type by defining it as a named, top-level schema type instead of an inline definition.
Here's how to fix your schema:
Step 1: Create a named image type
Create a new schema file (e.g., mainImageMedium.js or mainImageMedium.ts):
export default {
name: 'mainImageMedium',
title: 'HeaderBild Medium',
type: 'image',
fields: [
{
name: 'caption',
type: 'string',
title: 'Caption',
options: {
isHighlighted: true
}
}
]
}Step 2: Import and add it to your schema
Add this new type to your schema configuration (in your schema.js or sanity.config.ts):
import mainImageMedium from './schemas/mainImageMedium'
export default defineConfig({
// ... other config
schema: {
types: [
mainImageMedium,
// ... your other types
]
}
})Step 3: Reference it in your document
In your Asbrandpage document, reference the named type:
{
name: 'mainImageMedium',
title: 'HeaderBild Medium',
type: 'mainImageMedium' // Reference the named type instead of 'image'
}This approach is necessary because:
- GraphQL requires named types - Anonymous inline objects can't be represented in GraphQL's type system
- Better reusability - You can now use this image type across multiple documents
- Improved maintainability - Changes to the image structure only need to happen in one place
- Better TypeScript/type generation - Named types work better with TypeGen and other tooling
As explained in the Sanity documentation on lifting anonymous object types, this pattern also helps you think about your data model more globally and makes it easier to reason about your content structure when consuming the API from your application.
The key difference from your original code is that instead of defining the image inline with type: 'image' and fields: [...] directly in your document, you create a separate named schema type and then reference it by name. This gives GraphQL (and other tools) a proper type definition to work with.
Show original thread6 replies
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.