Generated banner for Sanity Best Practices
Generated logo for Sanity Best Practices

Sanity Best Practices

SanityOfficialPublished by Sanity

  • Skill
  • Tool integration
  • Software development
  • MIT
  • No issues found

From the author

Sanity development best practices for schema design, GROQ queries, TypeGen, Visual Editing, images, Portable Text, Studio structure, localization, migrations, Sanity Functions, webhooks, Blueprints, and framework integrations such as Next.js, Nuxt, Astro, Remix, SvelteKit, Angular, Hydrogen, the App SDK, and Studios or apps running in the Sanity Dashboard (defineApplication). Use this skill whenever working with Sanity schemas, defineType or defineField, GROQ or defineQuery, content modeling, Presentation or preview setups, Sanity-powered frontend integrations, event-driven content automation, documentEventHandler, defineDocumentFunction, defineMediaLibraryAssetFunction, @sanity/functions, @sanity/blueprints, sanity.blueprint.ts, event-driven content automation, or when reviewing and fixing a Sanity codebase.
— the description by Sanity

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a comprehensive collection of best practices, architectural patterns, and integration guides for the Sanity ecosystem. It covers the full development lifecycle, including schema design, GROQ query optimization, TypeGen configuration, and framework-specific integrations like Next.js, Angular, and Remix. It also includes guidance on infrastructure management via Blueprints, content automation with Sanity Functions, and building custom applications with the Sanity App SDK.

What it does

  • Provides standardized patterns for Sanity schema design and content modeling.
  • Offers integration guides for major frontend frameworks and the Sanity App SDK.
  • Defines best practices for GROQ query performance and type safety with TypeGen.
  • Outlines rules for media handling, including video asset management.
  • Details configuration for Sanity Studio structure and Visual Editing.
  • Explains infrastructure-as-code workflows using Sanity Blueprints.

When to use it

  • When starting a new Sanity project or onboarding team members.
  • When integrating Sanity with frameworks like Next.js, Astro, or Angular.
  • When optimizing GROQ queries or implementing type-safe data fetching.
  • When designing complex content schemas or implementing localization.
  • When setting up live previews, Visual Editing, or custom Studio structures.
  • When automating content workflows or managing infrastructure via Blueprints.

Advantages

  • Maintained by Sanity, ensuring alignment with current platform standards.
  • Reduces technical debt by enforcing consistent schema and query patterns.
  • Provides clear decision matrices for complex topics like video and localization.
  • Includes framework-specific guidance to accelerate frontend integration.
  • Promotes maintainable project structures and type-safe development workflows.

Usage examples

“What are the best practices for handling video in Sanity?”
The skill advises against using standard file assets for production video due to bandwidth costs, recommending the Sanity Media Library with Mux for Enterprise plans or dedicated services like Mux, YouTube, or Vimeo for others.
“How do I set up TypeGen for an Angular monorepo?”
The skill provides a configuration example for studio/sanity.cli.ts to point TypeGen at the Angular source files, ensuring generated types are correctly integrated into the Angular project.
“What is the recommended way to structure singleton documents?”
The skill recommends using explicit document IDs for singleton documents and controlling them via the Studio Structure, while letting Sanity generate IDs for all other document types.
“How should I fetch data in a React app using the App SDK?”
The skill mandates wrapping data-fetching components in Suspense, using documentId as a React key, and preferring useDocuments and useDocumentProjection over raw GROQ hooks.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/sanity-io/sanity-best-practices/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip sanity-best-practices.zip -d .agents/skills

Documentation by Sanity

Sanity Best Practices

Comprehensive best practices and integration guides for Sanity development, maintained by Sanity. Use the quick reference below to load only the one or two topic files that match the task.

When to Apply

Reference these guidelines when:

  • Setting up a new Sanity project or onboarding

  • Integrating Sanity with a frontend framework (Next.js, Nuxt, Astro, Remix, SvelteKit, Hydrogen)

  • Writing GROQ queries or optimizing performance

  • Designing content schemas

  • Implementing Visual Editing and live preview

  • Working with images, Portable Text, or page builders

  • Configuring Sanity Studio structure

  • Setting up TypeGen for type safety

  • Implementing localization

  • Migrating content from other systems

  • Building custom apps with the Sanity App SDK

  • Developing or deploying a Studio or app in the Sanity Dashboard

  • Managing infrastructure with Blueprints

  • Automating content workflows with Sanity Functions or webhooks

Global Rules

  • Let Sanity generate _id values for ordinary documents. Do not create deterministic UUIDs, slug-derived IDs, or legacy-system IDs when creating documents.

  • Model relationships with reference fields, then resolve related documents with GROQ lookups, source-key fields, or returned _id values from created documents.

  • Use explicit document IDs mainly for singleton documents controlled by Studio Structure, including localized singletons such as homePage-en.

Video

  • Do not store or serve video from Sanity file assets for production playback. File assets are delivered as raw downloads with no transcoding or adaptive streaming, and video traffic drives very high bandwidth usage and unexpectedly large bills.

  • On Enterprise plans with the video add-on, use Sanity Media Library for video: uploads are transcoded and streamed adaptively via Mux. Model video fields with defineVideoField() from sanity/media-library and play them with @mux/mux-player-react using the asset's playback ID.

  • On other plans, use a dedicated video service: install sanity-plugin-mux-input to upload and manage videos in your Mux account from the Studio, or host video on a platform such as YouTube or Vimeo and store only the embed URL in Sanity.

  • Small clips and short previews in a file field are acceptable, but any user-facing video at scale must go through Media Library or a streaming service.

Quick Reference

Integration Guides
  • get-started - Interactive onboarding for new Sanity projects

  • nextjs - Next.js App Router, Live Content API, standalone Studio

  • nuxt - Nuxt integration with @nuxtjs/sanity

  • angular - Angular integration with @sanity/client, signals, resource API

  • astro - Astro integration with @sanity/astro

  • remix - React Router / Remix integration

  • svelte - SvelteKit integration with @sanity/svelte-loader

  • hydrogen - Shopify Hydrogen with Sanity

  • project-structure - Standalone Studio and monorepo patterns

  • app-sdk - Custom applications with Sanity App SDK

  • dashboard - Studios and apps in the Sanity Dashboard: defineApplication, local dev, deploys, Dashboard hooks

  • blueprints - Infrastructure as Code: blueprint files, stacks, plan/deploy workflow, error recovery, CI deploys

  • functions - Automating content workflows with Sanity Functions and webhooks

Topic Guides
  • groq - GROQ query patterns, type safety, performance optimization

  • schema - Schema design, field definitions, validation, deprecation patterns

  • visual-editing - Presentation Tool, Stega, overlays, live preview

  • page-builder - Page Builder arrays, block components, live editing

  • portable-text - Rich text rendering and custom components

  • image - Image schema, URL builder, hotspots, LQIP, Next.js Image

  • studio-structure - Desk structure, singletons, navigation

  • typegen - TypeGen configuration, workflow, type utilities

  • seo - Metadata, sitemaps, Open Graph, JSON-LD

  • localization - i18n patterns, document vs field-level, locale management

  • migration - Content import overview (see also migration-html-import)

  • migration-html-import - HTML to Portable Text with @portabletext/block-tools

How to Use

Start with the single framework or topic guide that best matches the request, then read additional references only when the task crosses concerns. Use these reference files for detailed explanations and code examples:

references/groq.md
references/schema.md
references/nextjs.md

Each reference file contains:

  • Comprehensive topic or integration coverage

  • Incorrect and correct code examples

  • Decision matrices and workflow guidance

  • Framework-specific patterns where applicable

Files

references/remix.md


title: React Router (Remix) & Sanity Integration Rules description: Integration guide for React Router v7 (and Remix v2) with Sanity, including loaders and visual editing.

React Router (Remix) & Sanity Integration Rules

Version Note

The primary examples below use React Router v7 (the current shape — Remix v2 was renamed to React Router v7 starting with the v7 release). Import paths and the route-types file (./+types/<route>) come from the react-router package and the framework's typegen.

If you are on the older Remix v2 stack, the integration shape is identical; only the import paths differ:

React Router v7Remix v2
react-router@remix-run/node / @remix-run/react
import type { Route } from "./+types/<route>"import type { LoaderFunctionArgs } from "@remix-run/node" + useLoaderData<typeof loader>()
react-router.config.tsremix.config.js

1. Setup & Client Pattern

Scaffold a new React Router v7 app
npx create-react-router@latest my-app -y
cd my-app
npm install @sanity/client @sanity/react-loader @sanity/visual-editing @portabletext/react groq

-y accepts defaults. The Sanity packages cover server loaders (@sanity/react-loader, @sanity/client), live preview (@sanity/visual-editing), Portable Text rendering (@portabletext/react), and typed queries (groq).

To support both server-side fetching and client-side live previews, use the Split Loader Pattern.

A. Environment Variables

React Router runs on Vite. Any module reachable from a route component gets bundled into the client — process.env doesn't exist there and will throw ReferenceError: process is not defined on client-side route transitions (SSR will still work, which makes this trap easy to miss).

Split publishable values from secrets:

  • Publishable (projectId, dataset, apiVersion, studioUrl): prefix with VITE_ and read via import.meta.env. Safe to import from anywhere.

  • Secrets (read tokens, webhook secrets): keep unprefixed and read via process.env only inside *.server.ts files. Never re-export them from a shared module.

.env:

VITE_SANITY_PROJECT_ID=your-project-id
VITE_SANITY_DATASET=production
VITE_SANITY_API_VERSION=2026-02-01
VITE_SANITY_STUDIO_URL=http://localhost:3333
SANITY_API_READ_TOKEN=your-read-token

app/sanity/env.ts — browser-safe, publishable values only:

export const projectId = import.meta.env.VITE_SANITY_PROJECT_ID!
export const dataset = import.meta.env.VITE_SANITY_DATASET!
export const apiVersion = import.meta.env.VITE_SANITY_API_VERSION ?? '2026-02-01'
export const studioUrl = import.meta.env.VITE_SANITY_STUDIO_URL
B. Shared Loader (app/sanity/loader.ts)

Defines the store config (SSR enabled, client deferred).

import { createQueryStore } from '@sanity/react-loader'

export const {
  loadQuery,
  setServerClient,
  useQuery,
  useLiveMode,
} = createQueryStore({ client: false, ssr: true })
C. Server Loader (app/sanity/loader.server.ts)

Initializes the server client. Read the token directly from process.env here — do not import it from env.ts, or it will leak into the client bundle the moment any client-reachable module touches env.ts.

import { createClient } from '@sanity/client'
import { loadQuery, setServerClient } from './loader'
import { projectId, dataset, apiVersion, studioUrl } from './env'

const client = createClient({
  projectId,
  dataset,
  apiVersion,
  useCdn: true,
  token: process.env.SANITY_API_READ_TOKEN,
  stega: {
    // Stega encodes invisible markers into string fields for click-to-edit
    // overlays in the Presentation tool. Those markers can leak into copy/paste,
    // screen readers, and some downstream renderers, so only enable when actually
    // previewing — gate on an env var that's only set in preview environments.
    enabled: Boolean(studioUrl),
    studioUrl,
  },
})

setServerClient(client)

export { loadQuery }
D. Browser-safe Client + Image URL Builder (app/sanity/client.ts, app/sanity/image.ts)

Anything used by a route component runs in the browser too. Build a separate publishable-only client for things like the image URL builder:

// app/sanity/client.ts
import { createClient } from '@sanity/client'
import { projectId, dataset, apiVersion } from './env'

export const client = createClient({
  projectId,
  dataset,
  apiVersion,
  useCdn: true,
})
// app/sanity/image.ts
import imageUrlBuilder from '@sanity/image-url'
import { client } from './client'

const builder = imageUrlBuilder(client)
export const urlFor = (source: Parameters<typeof builder.image>[0]) => builder.image(source)

Install @sanity/image-url if you'll render images:

npm install @sanity/image-url
E. Queries (app/sanity/queries.ts)

Keep query definitions in one place so route loaders, components, and TypeGen all read the same source.

import { defineQuery } from "groq";

export const POSTS_QUERY = defineQuery(
  `*[_type == "post" && defined(slug.current)] | order(_createdAt desc){
    _id, title, slug
  }`
);

export const POST_QUERY = defineQuery(
  `*[_type == "post" && slug.current == $slug][0]{
    _id, title, body, image
  }`
);

2. Data Fetching (Loaders)

Use loadQuery from your server file in route loaders. Import the generated Route type from ./+types/<route> — React Router writes one type module per route file.

// app/routes/home.tsx
import type { Route } from "./+types/home";
import { loadQuery } from "~/sanity/loader.server";
import { POSTS_QUERY } from "~/sanity/queries";

export async function loader() {
  const initial = await loadQuery(POSTS_QUERY, {});
  return { initial, query: POSTS_QUERY, params: {} };
}

export default function Home({ loaderData }: Route.ComponentProps) {
  const { initial } = loaderData;
  // …pass to component
}

For Remix v2: replace Route.ComponentProps / Route.LoaderArgs with useLoaderData<typeof loader>() and LoaderFunctionArgs from @remix-run/node.

3. Dynamic Routes (:slug)

Register the dynamic route in app/routes.ts:

import { type RouteConfig, index, route } from "@react-router/dev/routes";

export default [
  index("routes/home.tsx"),
  route(":slug", "routes/post.tsx"),
] satisfies RouteConfig;

Then in app/routes/post.tsx:

import type { Route } from "./+types/post";
import { PortableText } from "@portabletext/react";
import { loadQuery } from "~/sanity/loader.server";
import { useQuery } from "~/sanity/loader";
import { urlFor } from "~/sanity/image";
import { POST_QUERY } from "~/sanity/queries";

export async function loader({ params }: Route.LoaderArgs) {
  const initial = await loadQuery(POST_QUERY, { slug: params.slug });
  return { initial, query: POST_QUERY, params: { slug: params.slug } };
}

export default function Post({ loaderData }: Route.ComponentProps) {
  const { initial, query, params } = loaderData;
  const { data: post } = useQuery(query, params, { initial });

  return (
    <article>
      <h1>{post?.title}</h1>
      {post?.image && (
        <img src={urlFor(post.image).width(1200).url()} alt={post.title ?? ""} />
      )}
      {post?.body && <PortableText value={post.body} />}
    </article>
  );
}

This route is the canonical shape that exposes the env trap: urlFor → client.ts → env.ts. If env.ts reads process.env, the route works under SSR (curl returns HTML) but the client-side <Link> navigation will throw ReferenceError: process is not defined in the browser console and React Router will hard-reload back to /.

4. Real-time Preview & Visual Editing

A. Use useQuery in Components

Import useQuery from your shared loader file.

import { useQuery } from "~/sanity/loader";

export default function Page({ loaderData }: Route.ComponentProps) {
  const { initial, query, params } = loaderData;

  const { data, encodeDataAttribute } = useQuery(query, params, { initial });

  return (
    <h1 data-sanity={encodeDataAttribute("title")}>
      {data?.title}
    </h1>
  );
}
B. Enable Live Mode (VisualEditing.tsx)

Create a component to handle the connection.

import { enableVisualEditing } from '@sanity/visual-editing'
import { useLiveMode } from '~/sanity/loader'
import { client } from '~/sanity/client' // Your browser-safe client
import { useEffect } from 'react'

export default function VisualEditing() {
  useEffect(() => enableVisualEditing(), [])
  useLiveMode({ client })
  return null
}

Render this component in root.tsx only when valid (e.g., check env vars or user session).

5. Stega Cleaning

When using data for logic (routing, classNames), use stegaClean.

import { stegaClean } from "@sanity/client/stega"
// ...
if (stegaClean(slug) === 'home') { ... }

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Sanity
Publisher
Sanity (Official)
Source
sanity-io/agent-toolkit · skills/sanity-best-practices · commit 3ed3a14
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Sanity.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download sanity-best-practices.zip