[NOW AVAILABLE] πŸ‘‹ Hey Content Agent, tell me what you do that other AI tools can’t β†’
Skip to content
Sanity
  • Content operations

    • Sanity Studio
    • Media Library
    • Canvas
    • Content AgentNew
    • Content Releases
    • Insights
    • App SDK

    Content backend

    • Content Lake
    • Live CDN
    • Compute
    • Agent Actions
    • MCP ServerNew
    a white background with orange and black dots on it

    The only platform powering content operations

    Start building for free
    Start building for free
  • Use Cases

    • Headless CMS
    • E-commerce
    • Marketing
    • Media and publishing
    • PIM
    • LMS
    • Build your own

    Users

    • Developers
    • Content Editors
    • Product Owners
    • Business Leaders
    a man sits on a fence next to a horse

    Tecovas strengthens their customer connections

    Read the story
    Read the story
  • Build and Share

    • Sanity 101
    • Sanity Learn
    • Frameworks
    • Templates
    • Tools and plugins
    • Schemas and snippets
    • Join our community

    Insight

    • Blog
    • Events
    • Customer stories
    • Guides
    A dark-themed collage showcasing branded merchandise including t-shirts, a cap, mug, tote bag, and socks, alongside various digital design elements and logos, prominently featuring "Sanity" branding.

    Grab your gear: The official Sanity swag store

    Read Grab your gear: The official Sanity swag store
  • Docs
  • Enterprise
  • Pricing
Sanity

  • Content operations

    • Sanity StudioHeadless CMS
    • Media LibraryCentralized asset management
    • CanvasAI-assisted, free-form writing
    • Content AgentNewAI for content operations
    • Content ReleasesStack and stage content updates
    • InsightsUnderstand content performance
    • App SDKRapidly build content apps

    Content backend

    • Content LakeThe content optimized database
    • Live CDNSimple, scalable, real-time
    • ComputeEvent handlers for content changes
    • Agent ActionsBuilt-in, content aware AI
    • MCP ServerNew
  • Use Cases

    • Headless CMS
    • E-commerce
    • Marketing
    • Media and publishing
    • PIM
    • LMS
    • Build your own

    Users

    • Developers
    • Content Editors
    • Product Owners
    • Business Leaders
  • Build and Share

    • Sanity 101A quick series covering key areas of Sanity to get you up to speed.
    • Sanity Learn
    • Frameworks
    • Templates
    • Tools and plugins
    • Schemas and snippets
    • Join our community

    Insight

    • Blog
    • Events
    • Customer stories
    • Guides
  • Docs
  • Enterprise
  • Pricing
Join our community on Discord
SubscribeΒ to our newsletter

Products

  • Sanity Studio
  • Media Library
  • Canvas
  • Content Agent
  • MCP Server
  • Content Releases
  • Insights
  • App SDK
  • Content Lake
  • Live CDN
  • Compute
  • Agent Actions
  • AI Assist
  • Use cases

Resources

  • Docs
  • Sanity 101
  • Sanity Learn
  • Tools and plugins
  • Frameworks
  • Templates
  • Schemas and snippets
  • Guides
  • Headless CMS explained
  • Resource library
  • Explainers
  • Enterprise CMS guides
  • Headless CMS Guides
  • Enhancing your CMS with AI
  • Compare Sanity
  • Glossary
  • Pricing

Company

  • Contact
  • Blog
  • Shop
  • Events
  • Careers
  • Changelog
  • Customer Stories
  • Agency Partners
  • Technology Partners

Trust and compliance

  • Privacy policy
  • Terms of service
  • Accessibility statement
  • Transparency statement
  • Security and compliance
  • Open Source Pledge

Keep in touch

Β© SANITY 2026

OSL, NOR (CET)

SFO, USA (PST)

Loading system status...
Change Site Theme
How-to guide

Flexible schemas
Type-safe queries

Get the best of both worldsβ€”Type safety and free form content modeling. This guide walks you through setting up a Sanity project, creating TypeScript types for your Sanity Studio schema types, and your front-end's GROQ queries.

Follow guideEmail me the guide

Sanity features in this guide

TypeGen

Create TypeScript types for your Sanity Studio schema types, as well as the results of GROQ queries. Giving you free-form content modeling as well as type safety.

TypeGen Docs

Sanity Studio

The customizable, React-based content editing dashboard configured with JavaScript. Run locally in a Vite development environment and deploy to your hostingβ€”or ours.

Learn more

GROQ

Think of it as "SQL for JSON," an open-standard query language developed at Sanity for powerful, flexible queries to fetch only the content you wantβ€”with the flexibility to augment the response how you like.

GROQ Docs

On your phone?

This guide requires a terminal. Email yourself this command + get an extended 60-day trial of Sanity's paid features to start building when you're back at your desk.

By submitting this form, you confirm that you have read and understood Sanity's Privacy Policy. This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The best of both worlds

If you have an existing Sanity project, you may prefer to read the TypeGen Docs for details on how to incorporate type-safety.

What's covered in this guide

You'll create a new free Sanity project, and generate TypeScript types for the Sanity Studio schema types and your front-end's GROQ queries.

Create a new project

Get started by clicking here to create a new free Sanity project using the Next.js template. Or use the command below to get started via the command line.

If you don't already have an account with Sanity, you'll be prompted to create one.

Building later? This guide requires a terminal. Email yourself this command + get an extended 60-day trial of Sanity's paid features to start building when you're back at your desk.

npm create sanity@latest -- --template sanity-io/sanity-template-nextjs-clean --coupon=flex-guide

Now inside this directory, start the development server.

npm run dev

You should now have two apps running:

  • http://localhost:3000 – Your Next.js app
  • http://localhost:3333 – Your Sanity Studio

These apps are separately configured in the following directories:

β”œβ”€ /nextjs-app
└─ /studio

The Sanity Studio is configured with code, edits you make to the configuration will render immediately in the development environment.

Content in Sanity Studio is written to a schemaless, cloud-hosted Dataset in what we call the Content Lake.

The Next.js app fetches content using Sanity Client with the GROQ query language.

Update Studio schema types

In your browser, open Sanity Studio. Click to the Structure tool in the header and create a new post type document.

In your code editor, open the schema type file for post type documents – post.ts – and add a new field called readingTime.

export default defineType({
  name: 'post',
  title: 'Posts',
  icon: DocumentTextIcon,
  type: 'document',
  fields: [
    // ...all other fields
    // πŸ‘‡ add this field
    defineField({
      name: 'readingTime',
      type: 'number'
    })
  ]
  // ...all other attributes
})

You should now see this field when editing a post type document.

Input field showing the word "reading time"

Update your types

TypeGen requires two steps to complete:

  1. A static "extraction" of your Sanity Studio schema configuration into JSON.
  2. Creating Types based on that schema and any GROQ queries the process finds in your code into TypeScript.

Extract your schema types

To update your Types, you'll first need to update the static extraction file from your Sanity Studio

Inside the Studio directory, run the following command:

npx sanity schema extract --enforce-required-fields

Inside your Next.js directory, run the following command:

npx sanity typegen generate

You should see a confirmation message like.

βœ… Generated TypeScript types for 31 schema types and 7 GROQ queries in 1 files into: ./sanity.types.ts

Now in the Next.js app, open app/components/Posts.tsx and see how the PostType has been extended to include your new readingTime field.

Code showing accessing a value from an object in TypeScript

However, PostType is a representation of the Sanity Studio schema, and may not match what your GROQ query requested. It is better to rely on the generated Types for query responses.

Update your GROQ query types

Sanity supports GraphQL, but GROQ is more widely used to query for Sanity content.

Open queries.ts and see how the Next.js app has multiple GROQ queries for Sanity content.

Inside the postFields variable, add the following line to the projection. This will use the value of your new readingTime field, to a return a boolean if it is not greater than 10.

const postFields = /* groq */ `
  // ... all other fields
  "isLongRead": readingTime > 10,
`
Code highlighting a new line in a GROQ query

Inside your Next.js directory, update the Types for query responses by re-running TypeGen:

npx sanity typegen generate

Now in Posts.tsx, you can update:

  • PostProps to use the AllPostsQueryResult type
  • Post to extract isLongRead from the props
// ...all other imports
import { AllPostsQueryResult } from "@/sanity.types";

// Update the `post` type to use query result
const Post = ({ post }: { post: AllPostsQueryResult[0] }) => {
  // You can now access `isLongRead`
  const { _id, title, slug, excerpt, date, isLongRead } = post;

Now the attributes available on the post prop match the GROQ query you wrote to fetch them.

Code demonstrating accessing an attribute from an object with TypeScript

Summary

You've now successfully created a new Sanity project, with a locally configured Sanity Studio.

You're able to rapidly update the schema types for content creators as well as query for that content in creative ways using GROQ.

All maintaining type-safety up and down your stack.

Go deeper

More resources

Course β€’ Sanity Learn

Day one content operations

Get a top-level understanding of the entire Sanity Content Operating System while building out a multi-application monorepo. With callouts to take other course material to go deeper.

View course

Sanity TypeGen

How to use Sanity TypeGen tooling to generate TypeScript definitions from Sanity Studio schemas and GROQ queries.

Of course, you should be able to type your content quickly!

product

Sanity TypeGen generates TypeScript types for GROQ queries. Combine the benefits of type-safe content with the most flexible way to query JSON.

Knut Melvær

Knut Melvær

Explore more guides

Sanity TypeGen

Learn how Sanity Studio's flexible content modeling and GROQ queries can be made type-safe.

Flexible schemas, Type-safe queries

Visual Editing

Separate content from code and let authors publish their own changes, while you focus on what you'd rather do.

Fix a typo without a PR

Live Content API

Make all your content real-time content. Build live-by-default applications without touching the refresh button or busting the cache.

Really easy real-time

What's next?

TypeGen, Sanity Studio and GROQ and are just a few parts of the Sanity Content Operating System. Get a fresh start on a new project or take a guided course for more.

Get startedSanity Learn
npm create sanity@latest -- --template sanity-io/sanity-template-nextjs-clean --coupon=flex-guide
β”œβ”€ /nextjs-app
└─ /studio
export default defineType({
  name: 'post',
  title: 'Posts',
  icon: DocumentTextIcon,
  type: 'document',
  fields: [
    // ...all other fields
    // πŸ‘‡ add this field
    defineField({
      name: 'readingTime',
      type: 'number'
    })
  ]
  // ...all other attributes
})
npx sanity schema extract --enforce-required-fields
npx sanity typegen generate
βœ… Generated TypeScript types for 31 schema types and 7 GROQ queries in 1 files into: ./sanity.types.ts
const postFields = /* groq */ `
  // ... all other fields
  "isLongRead": readingTime > 10,
`
npx sanity typegen generate
// ...all other imports
import { AllPostsQueryResult } from "@/sanity.types";

// Update the `post` type to use query result
const Post = ({ post }: { post: AllPostsQueryResult[0] }) => {
  // You can now access `isLongRead`
  const { _id, title, slug, excerpt, date, isLongRead } = post;