Sanity Best Practices
SanityOfficialPublished by Sanity
- Skill
- Tool integration
- Software development
- MIT
- No issues found
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/sanity-io/sanity-best-practices/downloadUnzip 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
_idvalues for ordinary documents. Do not create deterministic UUIDs, slug-derived IDs, or legacy-system IDs when creating documents.Model relationships with
referencefields, then resolve related documents with GROQ lookups, source-key fields, or returned_idvalues 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
fileassets 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()fromsanity/media-libraryand play them with@mux/mux-player-reactusing the asset's playback ID.On other plans, use a dedicated video service: install
sanity-plugin-mux-inputto 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
filefield 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 projectsnextjs- Next.js App Router, Live Content API, standalone Studionuxt- Nuxt integration with @nuxtjs/sanityangular- Angular integration with @sanity/client, signals, resource APIastro- Astro integration with @sanity/astroremix- React Router / Remix integrationsvelte- SvelteKit integration with @sanity/svelte-loaderhydrogen- Shopify Hydrogen with Sanityproject-structure- Standalone Studio and monorepo patternsapp-sdk- Custom applications with Sanity App SDKdashboard- Studios and apps in the Sanity Dashboard: defineApplication, local dev, deploys, Dashboard hooksblueprints- Infrastructure as Code: blueprint files, stacks, plan/deploy workflow, error recovery, CI deploysfunctions- Automating content workflows with Sanity Functions and webhooks
Topic Guides
groq- GROQ query patterns, type safety, performance optimizationschema- Schema design, field definitions, validation, deprecation patternsvisual-editing- Presentation Tool, Stega, overlays, live previewpage-builder- Page Builder arrays, block components, live editingportable-text- Rich text rendering and custom componentsimage- Image schema, URL builder, hotspots, LQIP, Next.js Imagestudio-structure- Desk structure, singletons, navigationtypegen- TypeGen configuration, workflow, type utilitiesseo- Metadata, sitemaps, Open Graph, JSON-LDlocalization- i18n patterns, document vs field-level, locale managementmigration- Content import overview (see alsomigration-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.mdEach reference file contains:
Comprehensive topic or integration coverage
Incorrect and correct code examples
Decision matrices and workflow guidance
Framework-specific patterns where applicable
Files
- ATTRIBUTION.mdAdded by AutoGineer873 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md5.4 KiB
- references/angular.md18.6 KiB
- references/app-sdk.md12.0 KiB
- references/astro.md4.9 KiB
- references/blueprints.md14.1 KiB
- references/dashboard.md6.5 KiB
- references/functions.md29.7 KiB
- references/get-started.md21.0 KiB
- references/groq.md14.4 KiB
- references/hydrogen.md6.8 KiB
- references/image.md3.3 KiB
- references/localization.md12.0 KiB
- references/migration-html-import.md5.2 KiB
- references/migration.md2.7 KiB
- references/nextjs.md16.3 KiB
- references/nuxt.md5.9 KiB
- references/page-builder.md8.2 KiB
- references/portable-text.md9.8 KiB
- references/project-structure.md3.5 KiB
- references/remix.md8.8 KiB
- references/schema.md12.4 KiB
- references/seo.md8.3 KiB
- references/studio-structure.md4.0 KiB
- references/svelte.md10.0 KiB
- references/typegen.md6.1 KiB
- references/visual-editing.md8.4 KiB
references/svelte.md
title: "SvelteKit & Sanity Integration Rules" description: Integration guide for SvelteKit with Sanity using @sanity/sveltekit, including Visual Editing and Preview Mode.
SvelteKit & Sanity Integration Rules
This guide uses the official @sanity/sveltekit package (Svelte 5 + SvelteKit 2). The older @sanity/svelte-loader does not work with Svelte 5 — its useQuery store returns empty on the client. Use @sanity/sveltekit instead.
1. Setup & Configuration
Scaffold a new SvelteKit app
npx sv@latest create my-app --template minimal --types ts --no-add-ons --install npm
cd my-app--template minimal is the bare app. --types ts enables TypeScript. --no-add-ons skips the add-on picker. --install <pm> chooses the package manager (npm, pnpm, yarn, or bun).
Installation
npm install @sanity/sveltekit @sanity/image-url @portabletext/svelte@sanity/sveltekit is the one-stop integration: it bundles @sanity/client, @sanity/visual-editing, @sanity/core-loader, groq, and friends, and re-exports createClient, defineQuery, groq, and stegaClean. Do not also install @sanity/client, @sanity/visual-editing, or groq directly — import them from @sanity/sveltekit. @sanity/image-url and @portabletext/svelte are not bundled, so add them separately.
Environment variables (.env.local)
PUBLIC_SANITY_PROJECT_ID=your-project-id
PUBLIC_SANITY_DATASET=production
PUBLIC_SANITY_API_VERSION=2026-05-15
PUBLIC_SANITY_STUDIO_URL=http://localhost:3333
SANITY_API_READ_TOKEN=SvelteKit's $env/static/public requires the PUBLIC_ prefix for any var read on the client. SANITY_API_READ_TOKEN must be declared (even empty) if any file imports it from $env/static/private, otherwise Vite throws at build time.
2. Files
src/lib/sanity/api.ts — env var resolution
import {
PUBLIC_SANITY_DATASET,
PUBLIC_SANITY_PROJECT_ID,
PUBLIC_SANITY_API_VERSION,
PUBLIC_SANITY_STUDIO_URL,
} from '$env/static/public'
function assertEnvVar<T>(value: T | undefined, name: string): T {
if (value === undefined || value === '') {
throw new Error(`Missing environment variable: ${name}`)
}
return value
}
export const dataset = assertEnvVar(PUBLIC_SANITY_DATASET, 'PUBLIC_SANITY_DATASET')
export const projectId = assertEnvVar(PUBLIC_SANITY_PROJECT_ID, 'PUBLIC_SANITY_PROJECT_ID')
export const apiVersion = PUBLIC_SANITY_API_VERSION || '2026-05-15'
export const studioUrl = PUBLIC_SANITY_STUDIO_URL || 'http://localhost:3333'src/lib/sanity/client.ts — public client
import {createClient} from '@sanity/sveltekit'
import {apiVersion, projectId, dataset, studioUrl} from '$lib/sanity/api'
export const client = createClient({
projectId,
dataset,
apiVersion,
useCdn: true,
stega: {studioUrl},
})Import createClient from @sanity/sveltekit, not @sanity/client. useCdn: true is for production reads; the server (preview) client below overrides to false.
src/lib/sanity/client.server.ts — server (preview) client
import {SANITY_API_READ_TOKEN} from '$env/static/private'
import {client} from '$lib/sanity/client'
export const serverClient = client.withConfig({
token: SANITY_API_READ_TOKEN,
useCdn: false,
stega: true,
})src/lib/sanity/queries.ts — queries + types
import {groq} from '@sanity/sveltekit'
export const postsQuery = groq`*[_type == "post" && defined(slug.current)] | order(_createdAt desc){
_id, _createdAt, title, slug, excerpt, mainImage, body
}`
export const postQuery = groq`*[_type == "post" && slug.current == $slug][0]{
_id, _createdAt, title, slug, excerpt, mainImage, body
}`
export interface Post {
_id: string
_createdAt: string
title?: string
slug: {current: string}
excerpt?: string
mainImage?: unknown
body?: unknown[]
}Use defineQuery instead of groq if you want TypeGen-friendly query definitions; both are re-exported from @sanity/sveltekit.
src/lib/sanity/image.ts — image URL builder
import {createImageUrlBuilder} from '@sanity/image-url'
import {client} from './client'
const builder = createImageUrlBuilder(client)
export function urlFor(source: unknown) {
return builder.image(source as never)
}Use the named createImageUrlBuilder export; the default export logs a deprecation warning at runtime.
3. Hooks & Locals
src/hooks.server.ts — wire preview + query loader
import {handlePreviewMode, handleQueryLoader, setServerClient} from '@sanity/sveltekit'
import {redirect} from '@sveltejs/kit'
import {sequence} from '@sveltejs/kit/hooks'
import {serverClient} from '$lib/sanity/client.server'
setServerClient(serverClient)
export const handle = sequence(
handlePreviewMode({
client: serverClient,
preview: {redirect},
}),
handleQueryLoader(),
)handlePreviewMode installs /preview/enable and /preview/disable endpoints, reads the preview cookie, and populates locals.sanity with {client, fetch, loadQuery, previewEnabled, previewPerspective, browserToken}. handleQueryLoader attaches loadQuery to locals.sanity for use in +page.server.ts / +layout.server.ts.
src/app.d.ts — typed locals
import type {SanityLocals} from '@sanity/sveltekit'
declare global {
namespace App {
interface Locals extends SanityLocals {}
}
}
export {}4. Layout: Preview + Visual Editing Providers
src/routes/+layout.server.ts — propagate previewEnabled
import type {LayoutServerLoad} from './$types'
export const load: LayoutServerLoad = (event) => {
const {previewEnabled} = event.locals.sanity
return {previewEnabled}
}src/routes/+layout.svelte — wrap children in providers (Svelte 5)
<script lang="ts">
import {PreviewMode, QueryLoader, VisualEditing} from '@sanity/sveltekit'
import type {LayoutProps} from './$types'
import {client} from '$lib/sanity/client'
const {children, data}: LayoutProps = $props()
// svelte-ignore state_referenced_locally
const {previewEnabled} = data
</script>
<PreviewMode enabled={previewEnabled}>
<VisualEditing enabled={previewEnabled}>
<QueryLoader enabled={previewEnabled} {client}>
{@render children()}
</QueryLoader>
</VisualEditing>
</PreviewMode>Svelte 5 idioms here are mandatory:
const {children, data} = $props()— notexport let data.{@render children()}— not<slot />.The
svelte-ignore state_referenced_locallycomment silences a warning about destructuring reactive props at module scope.
<VisualEditing> dynamically imports its component only when enabled === true, so a preview-off app never loads the React-Compiler-runtime chunk.
5. Data Fetching (Loaders + useQuery)
Posts list
src/routes/+page.server.ts:
import {postsQuery as query, type Post} from '$lib/sanity/queries'
import type {PageServerLoad} from './$types'
export const load: PageServerLoad = async ({locals}) => {
const {loadQuery} = locals.sanity
const initial = await loadQuery<Post[]>(query)
return {query, options: {initial}}
}The return shape {query, params?, options: {initial}} is what useQuery(data) on the client expects — don't change the field names.
src/routes/+page.svelte:
<script lang="ts">
import {useQuery} from '@sanity/sveltekit'
import type {Post} from '$lib/sanity/queries'
import type {PageProps} from './$types'
const {data}: PageProps = $props()
const query = $derived(useQuery<Post[]>(data))
const posts = $derived($query.data)
</script>
<h1>Posts</h1>
{#if posts?.length}
<ul>
{#each posts as post (post._id)}
<li><a href={`/post/${post.slug.current}`}>{post.title}</a></li>
{/each}
</ul>
{:else}
<p>No posts yet.</p>
{/if}Critical Svelte 5 pattern:
useQueryreturns a Svelte Readable store. Wrap in$derived(useQuery(data))so the store reference stays current across reactive updates.Subscribe via
$query(Svelte's auto-subscription) and read.data.Works on both SSR and client.
Post detail ([slug])
src/routes/post/[slug]/+page.server.ts:
import {postQuery as query, type Post} from '$lib/sanity/queries'
import type {PageServerLoad} from './$types'
export const load: PageServerLoad = async ({locals, params}) => {
const {loadQuery} = locals.sanity
const {slug} = params
const initial = await loadQuery<Post>(query, {slug})
return {query, params: {slug}, options: {initial}}
}src/routes/post/[slug]/+page.svelte:
<script lang="ts">
import {useQuery} from '@sanity/sveltekit'
import {PortableText} from '@portabletext/svelte'
import {urlFor} from '$lib/sanity/image'
import type {Post} from '$lib/sanity/queries'
import type {PageProps} from './$types'
const {data}: PageProps = $props()
const query = $derived(useQuery<Post>(data))
const post = $derived($query.data)
</script>
{#if post}
<article>
<h1>{post.title}</h1>
{#if post.mainImage}
<img src={urlFor(post.mainImage).width(800).url()} alt={post.title ?? ''} />
{/if}
{#if post.body}
<PortableText value={post.body} />
{/if}
</article>
{:else}
<p>Post not found.</p>
{/if}6. Stega Cleaning
When using fetched strings for logic (routing, classNames), strip the stega markers first.
import {stegaClean} from '@sanity/sveltekit'
// …
if (stegaClean(slug) === 'home') { /* … */ }7. Caveats
Yarn classic + Visual Editing.
@sanity/visual-editinglazy-loads a chunk that importsreact/compiler-runtime. Yarn classic doesn't auto-install peer deps, so users who flip preview mode on with yarn classic also needyarn add react react-dom. (Other package managers handle this automatically.)<VisualEditing>only loads this chunk whenenabled === true, so a default preview-off app is unaffected.No
<slot />. Svelte 5 layouts use{@render children()}.No
export let. Pages and components useconst {data} = $props().@sanity/image-urldefault export. Use the namedcreateImageUrlBuilder; the default export still works but logs a runtime deprecation warning.
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 or Sanity.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download sanity-best-practices.zip