CoursesTyped content with Sanity TypeGenConfiguring Sanity TypeGen for multiple-folder projects
Typed content with Sanity TypeGen

Configuring Sanity TypeGen for multiple-folder projects

Configure Sanity TypeGen to place its generated files in the right locations. Run the typegen command and interpret its results.
Log in to mark your progress for each Lesson and Task

Before you can generate types for GROQ query results, you must add some configuration that tells the TypeGen tooling where to look for those queries and where to put the file with the generated types.

Before diving in, it’s important to remember that you are still dependent on the schema.json file to generate types for your front end. You should also keep in mind that every time you change the Studio’s schema, you will have to rerun the extraction, and every time you change a GROQ query, you should update your types as well.

Add typegen configuration to your sanity.cli.ts file in your Studio folder with the following configuration:
import {defineCliConfig} from 'sanity/cli'
export default defineCliConfig({
api: {
projectId: 'your-project-id',
dataset: 'production'
},
/**
* TypeGen configuration
* Added in Sanity CLI v4.19.0
*/
typegen: {
path: '../day-one-with-sanity-nextjs/src/**/*.{ts,tsx,js,jsx}',
schema: 'schema.json',
generates: '../day-one-with-sanity-nextjs/src/sanity/types.ts'
}
})

This configuration method was introduced in Sanity CLI version 4.19.0. Previously, typegen configuration was stored in a separate sanity-typegen.json file, which is now deprecated. Using the sanity.cli.ts file keeps all your CLI configuration in one place.

The configuration works like this:

  • path configures where and which files Sanity TypeGen looks for GROQ queries. In this case, it will look through all the files in the front end’s src folder
  • schema is where to find the static schema representation. The default value is schema.json.
  • generates sets the path and the file name with the generated TypeScript definitions, in this case, in the front end’s sanity folder
The typegen configuration is now part of sanity.cli.ts as of version 4.19.0. If you're using an older version of the Sanity CLI, you may need to upgrade or use the deprecated sanity-typegen.json file instead.

With this configuration file in place, you can now run the typegen command:

Run the command from your Studio folder in your terminal
npx sanity typegen generate

If run successfully, you’ll see the result like this:

✔ Generated TypeScript types for 14 schema types and 0 GROQ queries in 0 files into: ../day-one-with-sanity-nextjs/src/sanity/types.ts
Open the types.ts file in your Next.js project folder and inspect its content

Notice how it says “0 GROQ queries,” this means you have to tweak your front end code to let Sanity TypeGen find your queries as well.

You have 3 uncompleted tasks in this lesson
0 of 3