Learn-skills.dev api-cms-sanity
Structured content platform — GROQ queries, schema definitions, @sanity/client, Portable Text, image handling, real-time listeners, mutations, TypeGen
git clone https://github.com/NeverSight/learn-skills.dev
T=$(mktemp -d) && git clone --depth=1 https://github.com/NeverSight/learn-skills.dev "$T" && mkdir -p ~/.claude/skills && cp -r "$T/data/skills-md/agents-inc/skills/api-cms-sanity" ~/.claude/skills/neversight-learn-skills-dev-api-cms-sanity && rm -rf "$T"
data/skills-md/agents-inc/skills/api-cms-sanity/SKILL.mdSanity Patterns
Quick Guide: Use Sanity for structured content management with GROQ queries, typed schemas via
/defineType, anddefineFieldfor data fetching. Always set@sanity/clientto a dated string, useapiVersionfor public reads, handle draft documents explicitly, useuseCdn: truefor image transformations, and render rich text with@sanity/image-url. Generate TypeScript types with@portabletext/react.sanity typegen generate
<critical_requirements>
CRITICAL: Before Using This Skill
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
, named constants)import type
(You MUST always set
on apiVersion
to a dated string like createClient
— omitting it uses a legacy API that may break)'2025-02-19'
(You MUST use
for public read queries and useCdn: true
when using a token or needing fresh data)useCdn: false
(You MUST use parameterized GROQ queries (
) for any dynamic values — never interpolate user input into GROQ strings)$param
(You MUST handle drafts explicitly — draft documents have
prefixed with _id
and are not returned by default with drafts.
)perspective: 'published'
(You MUST use
from defineQuery()
and assign queries to named variables for TypeGen type generation)groq
</critical_requirements>
Auto-detection: Sanity, sanity, @sanity/client, createClient, GROQ, groq, defineType, defineField, defineArrayMember, @sanity/image-url, urlFor, @portabletext/react, PortableText, portable text, block content, sanity.config, sanity.cli, typegen, sanity studio, content lake
When to use:
- Setting up
with@sanity/client
for data fetchingcreateClient - Writing GROQ queries (filters, projections, joins, ordering, slicing)
- Defining content schemas with
,defineType
,defineFielddefineArrayMember - Rendering Portable Text (block content) with
@portabletext/react - Generating image URLs with
(responsive images, crops, hotspots)@sanity/image-url - Performing mutations (create, patch, delete, transactions)
- Setting up real-time listeners with
client.listen() - Generating TypeScript types with Sanity TypeGen
Key patterns covered:
- Client setup with
andcreateClient
configurationapiVersion - GROQ query language: filters, projections, ordering, slicing, joins, references
- Schema definitions: document types, object types, arrays, references, images
- Portable Text rendering with custom components
- Image URL builder with responsive images and transformations
- Mutations: create, createOrReplace, patch, delete, transactions
- Real-time listeners via
client.listen() - TypeGen for type-safe GROQ queries with
defineQuery()
When NOT to use:
- GraphQL-only APIs (Sanity supports GROQ primarily; use GraphQL skill if needed)
- Direct database access (Sanity is a hosted content lake, not a database)
- Non-Sanity CMS platforms (use the dedicated skill for your CMS)
Detailed Resources:
- For decision frameworks and quick-reference tables, see reference.md
Client & GROQ:
- examples/core.md — Client setup, GROQ queries, error handling, TypeGen
Schemas:
- examples/schemas.md — defineType, defineField, document types, object types, references, images
Rich Content:
- examples/rich-content.md — Portable Text rendering, image URL builder, responsive images
Mutations & Real-time:
- examples/mutations.md — Create, patch, delete, transactions, real-time listeners
<philosophy>
Philosophy
Sanity is a structured content platform built around a real-time content lake, GROQ (Graph-Relational Object Queries) as its query language, and Sanity Studio as a customizable editing environment.
Core principles:
- Structured content — Content is defined by schemas (
,defineType
) that describe shape, validation, and editorial UI. Schemas are code, not configuration files.defineField - GROQ-first querying — GROQ lets you filter, project, join, and reshape data in a single query. Unlike REST or GraphQL, GROQ queries return exactly the shape you define in the projection.
- Content as data — Rich text is stored as Portable Text (a JSON-based specification), making it renderable in any frontend framework without vendor lock-in.
- API versioning — Every client must specify an
date string. This pins your code to a specific API behavior, preventing breaking changes from affecting production.apiVersion - CDN caching — Public read queries use
for edge-cached responses. Mutations and authenticated reads useuseCdn: true
for fresh data.useCdn: false - Type generation — Sanity TypeGen generates TypeScript types from both your schemas and GROQ queries, enabling end-to-end type safety from content model to frontend.
When to use Sanity:
- Content-driven websites and applications (blogs, marketing sites, documentation)
- Projects needing real-time collaborative editing in a customizable studio
- Multi-channel content delivery (web, mobile, IoT) from a single content source
- Teams wanting type-safe content queries with GROQ and TypeGen
When NOT to use:
- Transactional data requiring ACID guarantees (use a database)
- User-generated content at massive scale (Sanity is optimized for editorial content)
- Projects needing a self-hosted CMS (Sanity's content lake is hosted, though the Studio is open source)
<patterns>
Core Patterns
Pattern 1: Client Setup with createClient
Configure
@sanity/client with project ID, dataset, API version, and CDN preference. Always set apiVersion to a dated string and useCdn explicitly.
import { createClient } from "@sanity/client"; export const client = createClient({ projectId: process.env.SANITY_PROJECT_ID!, dataset: process.env.SANITY_DATASET!, apiVersion: "2025-02-19", // Pin to a specific API version date useCdn: true, // true for public reads, false for authenticated/fresh data });
For dual client setup (public + preview with token), see examples/core.md.
Pattern 2: GROQ Queries with Filters and Projections
GROQ queries combine filters, projections, ordering, and slicing. Always use
defineQuery() for TypeGen and $param for dynamic values.
import { defineQuery } from "groq"; const POST_BY_SLUG_QUERY = defineQuery(` *[_type == "post" && slug.current == $slug][0]{ _id, title, body, "author": author->{name, image} } `); const post = await client.fetch(POST_BY_SLUG_QUERY, { slug: "my-post" });
Never interpolate user input into GROQ strings -- always use
$param parameters to prevent GROQ injection. For advanced queries (combined queries, conditional projections), see examples/core.md.
Pattern 3: Schema Definitions with defineType and defineField
Define content structure with
defineType, defineField, and defineArrayMember from "sanity" for type safety and Studio UI.
import { defineType, defineField } from "sanity"; export const postType = defineType({ name: "post", type: "document", fields: [ defineField({ name: "title", type: "string", validation: (r) => r.required(), }), defineField({ name: "slug", type: "slug", options: { source: "title" } }), ], });
For complete schemas (images with hotspot, arrays, references, previews, object types), see examples/schemas.md.
Pattern 4: Portable Text Rendering
Render block content with
@portabletext/react. Define custom PortableTextComponents for non-standard blocks (images, code) and marks (links, highlights).
import { PortableText } from "@portabletext/react"; <PortableText value={body} components={components} />;
Do not use the deprecated
@sanity/block-content-to-react package. For full component examples, see examples/rich-content.md.
Pattern 5: Image URL Builder
Use
@sanity/image-url to generate optimized, responsive image URLs with crop and hotspot support.
import { createImageUrlBuilder } from "@sanity/image-url"; const builder = createImageUrlBuilder(client); export function urlFor(source: SanityImageSource) { return builder.image(source); } // Usage: urlFor(image).width(800).auto("format").url()
For responsive
srcSet patterns and image transformations, see examples/rich-content.md.
Pattern 6: Mutations (Create, Patch, Delete)
Use
@sanity/client methods for document mutations. Always call .commit() on patches and transactions.
await client.create({ _type: "post", title: "New Post" }); await client.patch("post-123").set({ title: "Updated" }).commit(); await client.delete("post-123");
For
createOrReplace, createIfNotExists, transactions, array inserts, and visibility options, see examples/mutations.md.
Pattern 7: Real-Time Listeners
Subscribe to document changes with
client.listen(). The listener only uses the filter portion of GROQ -- projections and ordering are ignored.
const subscription = client.listen(`*[_type == "post"]`).subscribe({ next: (update) => { /* update.transition: 'update' | 'appear' | 'disappear' */ }, error: (err) => console.error(err), }); subscription.unsubscribe(); // Cleanup when done
For production frontends, evaluate the newer Live Content API as a simpler alternative. For listener options and caveats, see examples/mutations.md.
Pattern 8: TypeGen for Type-Safe GROQ
Configure TypeGen in
sanity.cli.ts with overloadClientMethods: true for typed client.fetch results. Use defineQuery() from "groq" to make queries discoverable by TypeGen.
// sanity.cli.ts — set typegen.overloadClientMethods: true // queries/post-queries.ts — wrap queries with defineQuery() // sanity.types.ts — auto-generated result types const posts = await client.fetch(allPostsQuery); // Typed result
Inline query strings without
defineQuery() produce untyped (any) results. For full TypeGen configuration and workflow, see examples/core.md.
</patterns>
<decision_framework>
Decision Framework
useCdn: true vs false
Is the data public and non-personalized? ├─ YES → useCdn: true (edge-cached, fast) └─ NO → ├─ Using a token for authenticated reads? → useCdn: false ├─ Need real-time fresh data (preview)? → useCdn: false └─ Performing mutations? → useCdn: false
Draft Handling
Do you need draft documents? ├─ YES → Use perspective: 'previewDrafts' (requires token) ├─ NO → Use perspective: 'published' (default since API v2025-02-19) └─ Mixed (preview mode toggle)? └─ Create two clients: one public (useCdn: true), one preview (token + useCdn: false)
GROQ Query Return Shape
How many documents do you expect? ├─ One (by ID, slug, singleton) → Add [0] at end (returns object or null) ├─ Many (list, feed) → No slice suffix (returns array) └─ Paginated → Add [start...end] slice
Image Handling
How should images be delivered? ├─ Fixed size (thumbnails, avatars) → urlFor(img).width(W).height(H).url() ├─ Responsive (article images) → srcSet with multiple widths ├─ Format optimization → .auto('format') for WebP/AVIF └─ Cropped to aspect ratio → .width(W).height(H).fit('crop')
Mutation Method Selection
What operation do you need? ├─ Create new document → client.create() ├─ Create or fully replace → client.createOrReplace() (for singletons) ├─ Create only if missing → client.createIfNotExists() ├─ Update specific fields → client.patch(id).set({...}).commit() ├─ Remove fields → client.patch(id).unset([...]).commit() ├─ Multiple related changes → client.transaction()...commit() └─ Delete document → client.delete(id)
</decision_framework>
<red_flags>
RED FLAGS
High Priority Issues:
- Missing
on client — OmittingapiVersion
uses legacy API behavior that may change without notice. Always pin to a date string.apiVersion - String interpolation in GROQ queries — Interpolating user input into GROQ strings enables GROQ injection. Always use
parameters.$param - Using
with a token — CDN-cached responses ignore authentication tokens. Authenticated queries must useuseCdn: true
.useCdn: false - Accessing draft documents without a token — Drafts (
documents) require an API token anddrafts.*
. Without a token, drafts are invisible.perspective: 'previewDrafts'
Medium Priority Issues:
- Fetching all fields with
when only a few are needed — Over-fetching wastes bandwidth and CDN cache efficiency. Project only the fields you need.{...} - Missing
on patches —.commit()
withoutclient.patch(id).set({...})
does nothing — the mutation is never sent..commit() - Not using
for GROQ queries — TypeGen cannot generate types for queries that aren't wrapped indefineQuery()
or assigned to named variables.defineQuery() - Hardcoded project ID or dataset — Use environment variables; hardcoded values prevent environment switching and leak project details.
- Using deprecated
— Replaced by@sanity/block-content-to-react
. The old package is unmaintained.@portabletext/react
Common Mistakes:
- Forgetting
on array items in mutations — Every item in a Sanity array must have a unique_key
field. Mutations without_key
will fail._key - Using
with_id
—client.create()
generates a randomcreate()
. If you specify_id
and the document exists, it errors. Use_id
orcreateOrReplace()
for idempotent operations.createIfNotExists() - Not handling the case where
returns[0]
— A GROQ query ending innull
returns[0]
if no documents match, not an empty object.null - Expecting
to work with projections — The listener only uses the filter portion of a GROQ query. Projections, ordering, and slicing are ignored.client.listen()
Gotchas & Edge Cases:
- API version
changed default perspective — Before this version, the default perspective was2025-02-19
(includes drafts). After, it defaults toraw
. Existing code may break if you updatepublished
without accounting for this.apiVersion - CDN cache is eventual — After a mutation, CDN-cached queries (
) may return stale data for a few seconds. UseuseCdn: true
or add a small delay for consistency-critical reads after writes.useCdn: false - Slug fields store value in
— Query.current
, notslug.current
directly.slug
will never match.*[slug == "my-slug"] - Image fields require the full object for crop/hotspot — Passing only
toasset._ref
works for basic URLs but loses crop and hotspot metadata. Pass the entire image field object.urlFor() - Portable Text arrays need
on every block — When creating Portable Text content programmatically, every block and inline object needs a unique_key
._key
reconnects automatically — But there's no built-in guarantee against missed events during reconnection. For critical use cases, combine with periodic re-fetching.client.listen()- TypeGen requires
extraction first — Runschema.json
beforenpx sanity schema extract
. The extract step reads your Studio schemas and outputs a JSON representation.npx sanity typegen generate
</red_flags>
<critical_reminders>
CRITICAL REMINDERS
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
, named constants)import type
(You MUST always set
on apiVersion
to a dated string like createClient
— omitting it uses a legacy API that may break)'2025-02-19'
(You MUST use
for public read queries and useCdn: true
when using a token or needing fresh data)useCdn: false
(You MUST use parameterized GROQ queries (
) for any dynamic values — never interpolate user input into GROQ strings)$param
(You MUST handle drafts explicitly — draft documents have
prefixed with _id
and are not returned by default with drafts.
)perspective: 'published'
(You MUST use
from defineQuery()
and assign queries to named variables for TypeGen type generation)groq
Failure to follow these rules will cause unpredictable API behavior, GROQ injection vulnerabilities, and untyped query results.
</critical_reminders>