How to share TypeScript types between Sanity backend and frontend?

22 replies
Last updated: Jan 29, 2026
There something like this https://the-guild.dev/graphql/codegen for Sanity Client? I have my
/frontend
dir next to my
/backend
dir in a repo though so is the technique to move up the directory tree and import types from my
/backend
?
AI Update

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 generate

This will:

  1. Extract your schema to schema.json
  2. Scan your frontend code for GROQ queries (wrapped in defineQuery)
  3. 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.

Show original thread
22 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.

Was this answer helpful?