Discussion on generating types for Sanity Client and alternatives
Yes! Sanity has an official type generation tool called TypeGen that works similarly to GraphQL Codegen. It generates TypeScript types from both your schema and your GROQ queries.
For your monorepo setup with /frontend and /backend directories, you have a couple of good options:
Option 1: Generate types in backend, output to frontend
You can configure TypeGen to scan your frontend code and generate types directly into your frontend directory. Create a sanity-typegen.json configuration file in your /backend directory:
{
"path": "../frontend/src/**/*.{ts,tsx,js,jsx}",
"schema": "./schema.json",
"generates": "../frontend/src/sanity/types.ts"
}Then run from your backend directory:
npx sanity@latest schema extract
npx sanity@latest typegen generateThis will:
- Extract your schema to
schema.json - Scan your frontend code for GROQ queries (wrapped in
defineQuery) - Generate types directly into your frontend directory at the specified path
Option 2: Import types from backend
If you prefer to generate types in /backend and import them, that works perfectly:
// In your frontend
import type { Post, Author } from '../backend/sanity.types'Just make sure your TypeScript config allows this with appropriate path mappings or relative imports.
How it works
The TypeGen workflow generates types for:
- All your schema types
- GROQ query results (when you use
defineQuery) - Built-in Sanity types
For GROQ queries, wrap them with defineQuery to get type inference:
import { defineQuery } from 'next-sanity' // or 'groq'
const POSTS_QUERY = defineQuery(`*[_type == "post"]{title, slug}`)
const posts = await client.fetch(POSTS_QUERY) // fully typed as POSTS_QUERYResult!The defineQuery helper enables automatic type inference when using Sanity Client, so you don't need to manually specify types.
Re-run npx sanity typegen generate whenever you modify your schema or queries to keep types synchronized.
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.