sanity-best-practices

作成者: sanity-io

Sanity CMS開発におけるフレームワーク横断的な包括的なベストプラクティスと統合ガイド。Next.js、Nuxt、Astro、Remix、SvelteKit、Angularを含む10以上のフレームワーク統合を、フレームワーク固有のパターンとセットアップガイダンスとともにカバー。スキーマ設計、GROQクエリ最適化、ビジュアル編集、Portable Text、画像、TypeGen、ローカライゼーション、コンテンツ移行に関するトピックガイドを含む。タスクタイプに基づいて関連ガイドのみを読み込むためのクイックリファレンス構造を提供。

npx skills add https://github.com/sanity-io/agent-toolkit --skill sanity-best-practices

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 (including without a Sanity account via sanity new)
  • 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

Starting Without a Sanity Account

  • If the user asks to build or set up a new Sanity project and there is no Sanity login or Sanity MCP session (check with npx sanity@latest debug), do not stop and ask the user to log in or create a project manually.
  • Run npx sanity@latest new --instructions first and follow it to create an unclaimed project immediately (npx sanity@latest new "<project name>" --yes), scaffold or connect the Studio and frontend, seed sample content with the CLI (npx sanity@latest documents create seed.json from the Studio folder), and verify the app end to end.
  • Give the user the claim link and 72-hour expiry immediately so they can claim ownership while you keep building. Claiming does not interrupt work.
  • Keep the claim link out of git, issues, PRs, and shared channels. Leave SANITY_AUTH_TOKEN in sanity/.env.local: never print it, pass it inline, commit it, or put it in frontend env files or browser-exposed variables (NEXT_PUBLIC_*, SANITY_STUDIO_*).
  • For the full logged-in (sanity init) and no-account (sanity new) workflow, read references/get-started.md.

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.
  • Get the user's go-ahead before commands that change shared or production resources, can't be undone, or edit configuration outside the project: minting tokens, sanity deploy, blueprints deploy to a shared Stack, blueprints destroy, blueprints promote (one-way), CORS changes, mcp configure, and any delete or undeploy command (datasets, documents, tokens, CORS origins, GraphQL APIs, deployed Studios). Schema deploys and read-only commands such as blueprints plan don't need one during development.

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.

Studio Edit Links

  • Before building a URL that opens a document or a field in Studio (an "Edit in Studio" button, a link in a message or report), read https://www.sanity.io/docs/visual-editing/studio-edit-intent-links.md. Use the intent form, {studioUrl}/intent/edit/id={id};type={type};path={path}: it opens the document wherever it sits in the Structure tree, and path focuses one field.
  • Encode the path value with encodeURIComponent. Studio splits each parameter on =, so an unencoded body[_key=="abc"] is cut short at body[_key and the link focuses the wrong field.
  • Select array items by _key, not by index, in links that are stored or sent. Path syntax: https://www.sanity.io/docs/studio/how-form-paths-work.md
  • With only a Content Source Map and no document ID, use resolveEditUrl from @sanity/client/csm instead of building the URL by hand.

API & Robot Tokens

  • When a task needs a Sanity project or organization token (CI deploys, dataset writes, App SDK deploys) and you already have Sanity authentication (CLI login or Sanity MCP), offer to mint a scoped robot token instead of asking the user to copy one from Manage. Confirm the label, role, and where the token will be stored, then mint it. Only ask the user to create one themselves if you are not authenticated or lack token-creation permission.
  • Prefer the local CLI (@sanity/cli 8.19.0+; docs: https://www.sanity.io/docs/cli-reference/tokens.md) so you can pipe stdout JSON straight into the target secret store (such as gh secret set) without exposing the secret in agent output, logs, or committed files:
    • Project token: npx sanity@latest tokens create "<label>" --project <projectId> --role=<role> --yes --json (e.g. viewer, editor, deploy-studio; never administrator).
    • Organization token: npx sanity@latest tokens create "<label>" --organization <orgId> --grant <permission> --yes --json (e.g. --grant sdk-apps, --grant blueprints, --grant project:<projectId>=editor).
    • Add --expires-at <date> when the token is only needed for a one-off task. Tokens never expire by default.
  • When tokens is unavailable (for example, through Sanity MCP run_sanity_cli), use sanity api (docs: https://www.sanity.io/docs/cli-reference/cli-api.md; -f flags select POST automatically): sanity api projects/<projectId>/tokens -f label="<label>" -f roleName=<role> (returns key), or sanity api v2025-07-11/access/<resourceType>/<resourceId>/robots with bracket -f flags for nested memberships when --input is unavailable (returns token; docs: https://www.sanity.io/docs/http-reference/access-api.md).
  • MCP run_sanity_cli cannot pipe to a shell, so the raw secret lands in your tool output. Only mint through MCP when the local CLI is unavailable, and tell the user the token will pass through the conversation before you do. Always grant the narrowest role required and never echo or commit the token.

Quick Reference

Integration Guides

  • get-started - Setting up a new Sanity project with an account (sanity init) or without one (sanity new / sanity.new)
  • 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, Visual Editing
  • 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, classic Studio registration, 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

sanity-ioのその他のスキル

Agent Development
sanity-io
このスキルは、ユーザーが「エージェントを作成する」「エージェントを追加する」「サブエージェントを書く」「エージェントのフロントマター」「説明を使用するタイミング」「エージェント…」と依頼した場合に使用されるべきです。
code-review-and-quality
sanity-io
多軸コードレビューを実施します。変更をマージする前に使用してください。自分自身、他のエージェント、または人間が書いたコードをレビューする際に使用します。必要に応じて…
code-simplification
sanity-io
コードを明確にするために簡略化します。動作を変えずにコードをリファクタリングして明確にする場合に使用します。コードは動作するが、読みにくい、保守しにくい、拡張しにくい場合に使用します…
Command Development
sanity-io
このスキルは、ユーザーが「スラッシュコマンドを作成する」「コマンドを追加する」「カスタムコマンドを書く」「コマンド引数を定義する」「コマンドを使用する…」と依頼した場合に使用する必要があります。
content-experimentation-best-practices
sanity-io
コンテンツ実験の設計、実行、分析に関する構造化されたガイダンスで、コンバージョンとエンゲージメントを向上させます。仮説フレームワーク、指標の選択、サンプルサイズの計算、A/Bテストや多変量実験における統計的有意性検定を網羅。p値、信頼区間、検出力分析、結果解釈のためのベイズ手法に関する詳細なリソースを提供。フィールドレベルでバリアントを管理し、外部と接続するためのCMS統合パターンを含みます。
content-modeling-best-practices
sanity-io
構造化コンテンツモデリングのガイダンス:スキーマ設計、再利用性、マルチチャネル配信に対応。コンテンツをページではなくデータとして扱う、単一情報源の維持、将来のチャネルに対応した設計、編集者ワークフローの最適化といった基本原則を網羅。参照と埋め込みオブジェクトの判断基準、関心の分離、コンテンツ再利用パターンを提供。フラット、階層的、ファセット型アプローチのタクソノミーと分類ガイダンスを提示。対象範囲:...
create-agent-with-sanity-context
sanity-io
Sanity Contextを通じてSanityコンテンツへの構造化アクセスを持つAIエージェントを構築します。Sanityを活用したチャットボットのセットアップや、AIアシスタントをSanityに接続する際に使用します…
dial-your-context
sanity-io
Sanity Context MCPサーバー用のInstructionsフィールドコンテンツを作成するためのインタラクティブセッション。ユーザーがエージェントコンテキストの調整について言及する際は、このスキルを使用してください。…