Sanity-codegen query with projection not working as expected

17 replies
Last updated: Dec 1, 2025
Does anybody have experience with using sanity-codegen ? I feel like the query below should work. It works if I just use
*[_type == "country"]
but then it selects all of the values.
const allCountries = await client.query(
  '*[_type == "country"] { \'slug\': slug.current }'
);
AI Update

Your GROQ query *[_type == "country"] { 'slug': slug.current } is perfectly valid syntax and should work fine with sanity-codegen's client! The query itself isn't the problem.

However, I need to give you some important context: sanity-codegen has been archived and is no longer actively maintained. It's been superseded by Sanity's official TypeGen tooling, which was released in March 2024.

Without seeing the specific error you're getting, here are the most likely issues:

If you're getting type errors: The sanity-codegen client's query<T>() method should handle projections, but you might need to explicitly type the result:

interface CountrySlug {
  slug: string;
}

const allCountries = await client.query<CountrySlug[]>(
  '*[_type == "country"] { "slug": slug.current }'
);

Note: Use "slug" (with quotes) instead of 'slug' in your projection - both work in GROQ, but double quotes are the standard convention.

Recommended: Migrate to Official TypeGen

Since sanity-codegen is archived, I'd strongly recommend migrating to the official solution. It provides better type inference and is actively maintained:

npx sanity@latest typegen generate

Then use defineQuery for automatic type inference:

import { defineQuery } from 'next-sanity'; // or 'groq'
import { sanityFetch } from './lib/client';

const COUNTRIES_QUERY = defineQuery(
  '*[_type == "country"] { "slug": slug.current }'
);

const allCountries = await sanityFetch({ query: COUNTRIES_QUERY });
// TypeScript automatically knows the shape!

The official TypeGen creates a sanity.types.ts file with types for your entire schema and automatically infers types from your GROQ queries - no manual type annotations needed.

If you want to stick with sanity-codegen for now, can you share the specific error message you're seeing? That would help diagnose whether it's a type issue, runtime error, or something else.

Show original thread
17 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?