See AI content operations in action at Braze. Join the live session April 14th
How-to guide

Flexible schemas
Type-safe queries

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?

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:

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.

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.