← All packs

skill pack
Sanity
Sanity's skills for content modelling, GROQ, Studio and SEO.
10 skills by Sanity · sanity-io/agent-toolkit · MIT licence · checked on 18 Nov 2026
content-experimentation-best-practicesContent experimentation and A/B testing guidance covering experiment design, hypotheses, metrics, sample size, statistical foundations, CMS-managed variants, and common analysis pitfalls. Use this skill when planning experiments, setting up variants, choosing success metrics, interpreting statistical results, or building experimentation workflows in a CMS or frontend stack.ReadClose
--- name: content-experimentation-best-practices description: Content experimentation and A/B testing guidance covering experiment design, hypotheses, metrics, sample size, statistical foundations, CMS-managed variants, and common analysis pitfalls. Use this skill when planning experiments, setting up variants, choosing success metrics, interpreting statistical results, or building experimentation workflows in a CMS or frontend stack. --- # Content Experimentation Best Practices Principles and patterns for running effective content experiments to improve conversion rates, engagement, and user experience. ## When to Apply Reference these guidelines when: - Setting up A/B or multivariate testing infrastructure - Designing experiments for content changes - Analyzing and interpreting test results - Building CMS integrations for experimentation - Deciding what to test and how ## Core Concepts ### A/B Testing Comparing two variants (A vs B) to determine which performs better. ### Multivariate Testing Testing multiple variables simultaneously to find optimal combinations. ### Statistical Significance The confidence level that results aren't due to random chance. ### Experimentation Culture Making decisions based on data rather than opinions (HiPPO avoidance). ## References Start with the reference that matches the current problem, such as design, statistics, CMS integration, or pitfalls. See `references/` for detailed guidance: - `references/experiment-design.md` — Hypothesis framework, metrics, sample size, and what to test - `references/statistical-foundations.md` — p-values, confidence intervals, power analysis, Bayesian methods - `references/cms-integration.md` — CMS-managed variants, field-level variants, external platforms - `references/common-pitfalls.md` — 17 common mistakes across statistics, design, execution, and interpretation
Original on GitHubcontent-modeling-best-practicesStructured content modeling guidance for schema design, content architecture, content reuse, references versus embedded objects, separation of concerns, and taxonomies across Sanity and other headless CMSes. Use this skill when designing or refactoring content types, deciding field shapes, debating reusable versus nested content, planning omnichannel content models, or reviewing whether a schema is too page-shaped or presentation-driven.ReadClose
--- name: content-modeling-best-practices description: Structured content modeling guidance for schema design, content architecture, content reuse, references versus embedded objects, separation of concerns, and taxonomies across Sanity and other headless CMSes. Use this skill when designing or refactoring content types, deciding field shapes, debating reusable versus nested content, planning omnichannel content models, or reviewing whether a schema is too page-shaped or presentation-driven. --- # Content Modeling Best Practices Principles for designing structured content that's flexible, reusable, and maintainable. These concepts apply to any headless CMS but include Sanity-specific implementation notes. ## When to Apply Reference these guidelines when: - Starting a new project and designing the content model - Evaluating whether content should be structured or free-form - Deciding between references and embedded content - Planning for multi-channel content delivery - Refactoring existing content structures ## Core Principles 1. **Content is data, not pages** — Structure content for meaning, not presentation 2. **Single source of truth** — Avoid content duplication 3. **Future-proof** — Design for channels that don't exist yet 4. **Editor-centric** — Optimize for the people creating content ## References Start with the reference that matches the modeling decision in front of you, instead of loading every topic at once. See `references/` for detailed guidance on specific topics: - `references/separation-of-concerns.md` — Separating content from presentation - `references/reference-vs-embedding.md` — When to use references vs embedded objects - `references/content-reuse.md` — Content reuse patterns and the reuse spectrum - `references/taxonomy-classification.md` — Flat, hierarchical, and faceted classification
Original on GitHubportable-text-conversionConvert HTML and Markdown content into Portable Text blocks for Sanity. Use when migrating content from legacy CMSs, importing HTML or Markdown into Sanity, building content pipelines that ingest external content, converting rich text between formats, or programmatically creating Portable Text documents. Covers @portabletext/markdown (markdownToPortableText), @portabletext/block-tools (htmlToBlocks), custom deserializers, and the Portable Text specification for manual block construction.ReadClose
--- name: portable-text-conversion description: Convert HTML and Markdown content into Portable Text blocks for Sanity. Use when migrating content from legacy CMSs, importing HTML or Markdown into Sanity, building content pipelines that ingest external content, converting rich text between formats, or programmatically creating Portable Text documents. Covers @portabletext/markdown (markdownToPortableText), @portabletext/block-tools (htmlToBlocks), custom deserializers, and the Portable Text specification for manual block construction. license: MIT metadata: author: sanity version: "1.0.0" --- # Portable Text Conversion Convert external content (HTML, Markdown) into Portable Text for Sanity. Three main approaches: 1. **`markdownToPortableText`** — Convert Markdown directly using `@portabletext/markdown` (recommended for Markdown) 2. **`htmlToBlocks`** — Parse HTML into PT blocks using `@portabletext/block-tools` (for HTML migration) 3. **Manual construction** — Build PT blocks directly from any source (APIs, databases, etc.) ## Portable Text Specification Understand the target format before converting. PT is an array of blocks: ```json [ { "_type": "block", "_key": "abc123", "style": "normal", "children": [ {"_type": "span", "_key": "def456", "text": "Hello ", "marks": []}, {"_type": "span", "_key": "ghi789", "text": "world", "marks": ["strong"]} ], "markDefs": [] }, { "_type": "block", "_key": "jkl012", "style": "h2", "children": [ {"_type": "span", "_key": "mno345", "text": "A heading", "marks": []} ], "markDefs": [] }, { "_type": "image", "_key": "pqr678", "asset": {"_type": "reference", "_ref": "image-abc-200x200-png"} } ] ``` **Key rules:** - Every block and span needs `_key` (unique within the array) - `_type: "block"` is for text blocks; custom types use their own `_type` - `markDefs` holds annotation data; `marks` on spans reference `markDefs[*]._key` or are decorator strings - Lists use `listItem` ("bullet" | "number") and `level` (1, 2, 3...) on regular blocks ## Conversion Rules Read the rule file matching your source format: - **Markdown → Portable Text**: `rules/markdown-to-pt.md` — `@portabletext/markdown` with `markdownToPortableText` (recommended) - **HTML → Portable Text**: `rules/html-to-pt.md` — `@portabletext/block-tools` with `htmlToBlocks` - **Manual PT Construction**: `rules/manual-construction.md` — build blocks programmatically from any source > **Note:** `@sanity/block-tools` is the legacy package name. Always use `@portabletext/block-tools` for new projects. The API is the same.Original on GitHubportable-text-serializationRender and serialize Portable Text to React, Svelte, Vue, Astro, HTML, Markdown, and plain text. Use when implementing Portable Text rendering in any frontend framework, building custom serializers for non-standard block types, converting Portable Text to HTML strings server-side, converting Portable Text to Markdown, extracting plain text from Portable Text, or troubleshooting rendering issues with marks, blocks, lists, or custom types.ReadClose
--- name: portable-text-serialization description: Render and serialize Portable Text to React, Svelte, Vue, Astro, HTML, Markdown, and plain text. Use when implementing Portable Text rendering in any frontend framework, building custom serializers for non-standard block types, converting Portable Text to HTML strings server-side, converting Portable Text to Markdown, extracting plain text from Portable Text, or troubleshooting rendering issues with marks, blocks, lists, or custom types. license: MIT metadata: author: sanity version: "1.0.0" --- # Portable Text Serialization Render Portable Text content across frameworks using the `@portabletext/*` library family. Each library follows the same component-mapping pattern: you provide a `components` object that maps PT node types to framework-specific renderers. ## Portable Text Structure (Quick Reference) PT is an array of blocks. Each block has `_type`, optional `style`, `children` (spans), `markDefs`, `listItem`, and `level`. ``` Root array ├── block (_type: "block") │ ├── style: "normal" | "h1" | "h2" | "blockquote" | ... │ ├── children: [span, span, ...] │ │ └── span: { _type: "span", text: "...", marks: ["strong", "<markDefKey>"] } │ ├── markDefs: [{ _key, _type: "link", href: "..." }, ...] │ ├── listItem: "bullet" | "number" (optional) │ └── level: 1, 2, 3... (optional, for nested lists) ├── custom block (_type: "image" | "code" | any custom type) └── ...more blocks ``` **Marks** come in two forms: - **Decorators**: string values in `marks[]` like `"strong"`, `"em"`, `"underline"`, `"code"` - **Annotations**: keys in `marks[]` referencing entries in `markDefs[]` (e.g., links, internal references) ## Component Mapping Pattern (All Frameworks) Every `@portabletext/*` library accepts a `components` object with these keys: | Key | Renders | Props/Data | |-----|---------|------------| | `types` | Custom block/inline types (image, code, CTA) | `value` (the block data) | | `marks` | Decorators + annotations | `children` + `value` (mark data) | | `block` | Block styles (h1, normal, blockquote) | `children` | | `list` | List wrappers (ul, ol) | `children` | | `listItem` | List items | `children` | | `hardBreak` | Line breaks within a block | — | ## Framework-Specific Rules Read the rule file matching your framework: - **React / Next.js**: `rules/react.md` — `@portabletext/react` or `next-sanity` - **Svelte / SvelteKit**: `rules/svelte.md` — `@portabletext/svelte` - **Vue / Nuxt**: `rules/vue.md` — `@portabletext/vue` - **Astro**: `rules/astro.md` — `astro-portabletext` - **HTML (server-side)**: `rules/html.md` — `@portabletext/to-html` - **Markdown**: `rules/markdown.md` — `@portabletext/markdown` - **Plain text extraction**: `rules/plain-text.md` — `@portabletext/toolkit` ### Additional Community Serializers These are listed on [portabletext.org](https://www.portabletext.org/integrations/serializers/) but don't have dedicated rule files: | Target | Package | |--------|---------| | React Native | `@portabletext/react-native-portabletext` | | React PDF | `@portabletext/react-pdf-portabletext` | | Solid | `solid-portabletext` | | Qwik | `portabletext-qwik` | | Shopify Liquid | `portable-text-to-liquid` | | PHP | `sanity-php` (SanityBlockContent class) | | Python | `portabletext-html` | | C# / .NET | `dotnet-portable-text` | | Dart / Flutter | `flutter_sanity_portable_text` | ## Common Patterns (All Frameworks) ### Custom Types Need Explicit Components PT renderers only handle standard blocks by default. Custom types (`image`, `code`, `callToAction`, etc.) require explicit component mappings — they won't render otherwise. ### Keep Components Object Stable In React/Vue, define `components` outside the render function or memoize it. Recreating on every render causes unnecessary re-renders. ### Handle Missing Components Gracefully All libraries accept `onMissingComponent` to control behavior when encountering unknown types: - `false` — suppress warnings - Custom function — log or report ### Querying PT with GROQ Always expand references inside custom blocks: ```groq body[]{ ..., _type == "image" => { ..., asset-> }, markDefs[]{ ..., _type == "internalLink" => { ..., "slug": @.reference->slug.current } } } ```Original on GitHubsanity-best-practicesSanity 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, building links that open a document or field in Sanity Studio, or when reviewing and fixing a Sanity codebase.ReadClose
--- name: sanity-best-practices description: 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, building links that open a document or field in Sanity Studio, or when reviewing and fixing a Sanity codebase. --- # 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. ## 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. ## 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 applicableOriginal on GitHubsanity-form-component-suspenseFix a Sanity Studio custom form component (components.input, components.field, components.item, or a plugin's form.components) that suspends without its own Suspense boundary, so it loads without layout shift and never blocks new documents. Use when the console warns "The custom input/field/item component ... suspended without a <Suspense> boundary of its own" or "A form component ... suspended without a <Suspense> boundary of its own", when a custom form component uses React.lazy, use(), App SDK hooks (useDocumentProjection, useQuery, useDocument) or another suspending data library, or when a field or array item shows a skeleton that never goes away on new documents.ReadClose
--- name: sanity-form-component-suspense description: Fix a Sanity Studio custom form component (components.input, components.field, components.item, or a plugin's form.components) that suspends without its own Suspense boundary, so it loads without layout shift and never blocks new documents. Use when the console warns "The custom input/field/item component ... suspended without a <Suspense> boundary of its own" or "A form component ... suspended without a <Suspense> boundary of its own", when a custom form component uses React.lazy, use(), App SDK hooks (useDocumentProjection, useQuery, useDocument) or another suspending data library, or when a field or array item shows a skeleton that never goes away on new documents. --- # Custom form components that suspend Studio puts a fallback boundary around every field and every array item, so one suspending component cannot blank the form. That fallback is a generic skeleton: it does not know the size of what it replaces, so the form shifts when the component loads, and Studio warns about it in the console. The fix always lives in your code: declare a `Suspense` around the part that suspends, with a fallback that takes the same space as what it stands in for. Any boundary you declare is closer to what suspends than Studio's, so it always wins and nothing warns. That includes a boundary in a custom field around `props.renderDefault(props)`, which also covers the field's input: use it when one fallback should cover both, for example a lazy input that also fetches. ## Workflow 1. **Find the component.** The warning names the custom components declared for that field or item (`components.field`, `.input` or `.item`), the path, the document type and the schema type, and logs the components themselves; click one in the browser console to open its source. Production builds minify the names, so use the path and document type there. When the schema type declares none, the warning starts with "A form component" and the culprit is usually a plugin's `form.components`. React DevTools' Suspense tab shows which component actually suspended. 2. **Find what suspends.** Usually one of: `React.lazy`, `use(promise)`, an App SDK hook (`useDocumentProjection`, `useDocument`, `useQuery`, `useDocuments`), or a library in suspense mode (`useSuspenseQuery`). 3. **Move it into its own component** if it is not already, and wrap only that component in `<Suspense>` inside the custom component. Keep `props.renderDefault(props)` outside the boundary, so the built-in input, field or item never unmounts (and never loses focus while someone types) when the async part suspends again. 4. **Reserve the space.** The fallback must have the size of the loaded UI: - Additive UI (warnings, previews, counts): render it after `renderDefault` so it never pushes the rest down, and give the fallback the height of one loaded row. - A whole component that loads lazily: a skeleton with the component's height, not `null`. - Array items: the list is virtualized and measures each row, so an item fallback that is shorter or taller than the loaded row makes the rows below it jump. Match the row height. 5. **Do not suspend on a document that does not exist yet.** A new document only exists once the first edit creates it, and SDK hooks that read the current document wait for it forever. Gate on `useFormValue(['_createdAt'])`: it is unset until the document exists. 6. **Keep promises stable.** A promise created during render, in `useState` or in `useMemo` is thrown away while the component suspends on mount, so `use()` gets a new one every retry and never settles. Use the SDK hooks, a module-scope cache keyed by the inputs, or a data library. 7. **Verify.** Open a new document of the type and an existing one: the warning is gone, the rest of the form is editable right away, and nothing moves when the async part lands. ## Example ```tsx import {createDocumentHandle, useDocumentProjection} from '@sanity/sdk-react' import {Card, Skeleton, Stack, Text} from '@sanity/ui' import {Suspense} from 'react' import {type ArrayOfObjectsInputProps, getPublishedId, useFormValue} from 'sanity' export function ModelSizeInput(props: ArrayOfObjectsInputProps) { const documentId = useFormValue(['_id']) as string const documentExists = Boolean(useFormValue(['_createdAt'])) const hasModels = (props.value?.length ?? 0) > 0 return ( <Stack gap={3}> {props.renderDefault(props)} {documentExists && hasModels ? ( <Suspense fallback={<Skeleton radius={2} style={{height: 33}} animated />}> <ModelSizeWarnings documentId={getPublishedId(documentId)} /> </Suspense> ) : null} </Stack> ) } function ModelSizeWarnings(props: {documentId: string}) { const {data} = useDocumentProjection<{missing: number}>({ ...createDocumentHandle({documentType: 'product', documentId: props.documentId}), projection: `{"missing": count(models[!defined(@->size)])}`, }) return ( <Card padding={2} radius={2} tone={data.missing > 0 ? 'critical' : 'positive'}> <Text size={1}>{data.missing} models are missing a size</Text> </Card> ) } ``` The skeleton's height matches the one-line card it stands in for. If the loaded UI's height varies, reserve the most common case and keep the variable part below the input.Original on GitHubsanity-migrationPlans, implements, and reviews migrations from other CMSes and content systems into Sanity. Use when migrating or replatforming to Sanity from AEM, Adobe Experience Manager, Contentful, Strapi, Webflow, WordPress, Payload, Drupal, Markdown/MDX/frontmatter files, WXR/XML exports, CMS APIs, database dumps, static HTML, or when designing extraction, transformation, Portable Text conversion, asset migration, redirects, validation, and cutover workflows.ReadClose
--- name: sanity-migration description: Plans, implements, and reviews migrations from other CMSes and content systems into Sanity. Use when migrating or replatforming to Sanity from AEM, Adobe Experience Manager, Contentful, Strapi, Webflow, WordPress, Payload, Drupal, Markdown/MDX/frontmatter files, WXR/XML exports, CMS APIs, database dumps, static HTML, or when designing extraction, transformation, Portable Text conversion, asset migration, redirects, validation, and cutover workflows. --- # Sanity Migration Use this skill for CMS-to-Sanity migration work. Treat migration as a content strategy and ETL project, not a blind lift-and-shift. ## Required Workflow 1. Read `references/general.md` first. 2. If the source platform is known, also read its guide: - AEM / Adobe Experience Manager: `references/aem.md` - Contentful: `references/contentful.md` - Strapi: `references/strapi.md` - Webflow: `references/webflow.md` - WordPress / WXR / Elementor: `references/wordpress.md` - Payload: `references/payload.md` - Drupal: `references/drupal.md` - Markdown / MDX / frontmatter files: `references/markdown.md` 3. Before writing code, produce a short migration plan covering source access, content scope, schema decisions, extraction, transformation, import, validation, redirects, and cutover. 4. Prefer deterministic, repeatable scripts for real migrations. Write and review migration scripts, mappings, and validation checks; do not rely on one-off content operations for large content volumes. ## Deliverables to Produce For implementation or planning tasks, produce these artifacts or explain why they are not needed: - Content inventory: source types, counts, locales, status/draft scope, assets, and relationship types. - Source-to-Sanity mapping: document types, object types, references, Portable Text fields, asset fields, IDs, and skipped content. - Extraction approach: credentials/access needed, API/export commands, raw snapshot location, and known blind spots. - Transform/import plan: deterministic IDs, write order, asset handling, rich text conversion, validation, and rerun strategy. - Cutover plan: delta sync/content freeze, redirects, broken-link checks, SEO metadata, and manual cleanup. ## Defaults - Use stable document IDs derived from source IDs, slugs, paths, or hashes. - Use `createOrReplace`, `createIfNotExists`, or `sanity datasets import --replace` so reruns converge. - Snapshot extracted source data to disk before transforming it. - Import or create referenced documents before documents that reference them. - Convert rich text to Portable Text instead of storing raw HTML or Markdown strings. - Upload assets to Sanity or the Media Library; do not leave production content dependent on legacy CDN URLs. - Track per-document quality issues and produce a validation summary before cutover. - Preserve legacy URLs and source IDs for redirects, QA, and future debugging. ## Sanity Guardrails - Model what content is, not how the old site rendered it. - Use documents for reusable or independently managed entities; use objects for content owned by one document. - Use `defineType`, `defineField`, and `defineArrayMember` if authoring Sanity schemas. - Use image/file fields with uploaded Sanity assets or Media Library assets, not legacy CDN URLs. - Use Portable Text arrays for rich text and custom blocks; do not store raw HTML as the canonical body. - Run schema extraction and TypeGen after schema or GROQ query changes when the project uses TypeScript. - Deploy or apply schema changes before using MCP/content tools against the target dataset. For deeper Sanity implementation guidance, use `sanity-best-practices` if it is already available. If it is not installed, tell the user they can add it with: ```bash npx skills add sanity-io/agent-toolkit --skill sanity-best-practices ``` ## Stop and Ask Stop before coding when any of these are unclear: - Source access path, credentials, export file, or database connection. - Target Sanity project/dataset or whether a scratch dataset should be used. - Draft, archived, scheduled, locale, or version history scope. - Whether media files should be migrated and whether asset URLs/files are accessible. - Whether the destination schema exists or should be designed as part of the migration. ## Do Not Do This - Do not create random IDs for source-backed documents. - Do not fetch-then-create referenced documents; use deterministic IDs and `createIfNotExists`/`createOrReplace`. - Do not run bulk migrations through MCP content tools when NDJSON or scripts are appropriate. - Do not flatten locale fallback values into translations unless requested. - Do not leave TODOs for required media, authors, references, or rich text conversion. - Do not declare a migration done without count checks, sample checks, reference checks, and route/redirect checks. ## Reference Map Use `references/general.md` for shared migration principles and the platform references for source-specific extraction routes, modeling traps, and validation checks. For source systems not explicitly covered, apply `references/general.md` and adapt the closest platform pattern: - API-first CMSes: start from Contentful, Strapi, or Payload. - Monolithic/page-builder systems: start from WordPress, Drupal, Webflow, or AEM. - HTML-heavy exports: start from the WordPress and Webflow rich-text guidance. - Markdown-first sources: start from `references/markdown.md`.
Original on GitHubsanity-singletonsConfigure singleton documents in a Sanity Studio using the document.singletons registry. Use when a developer wants a fixed-id document (settings, navigation, footer) edited in place, hidden from the default content list, with no "create new" or "duplicate" affordances — or when migrating a userland singleton implementation or a third-party singleton plugin (e.g. sanity-plugin-singleton-management) to the first-class API.ReadClose
--- name: sanity-singletons description: Configure singleton documents in a Sanity Studio using the document.singletons registry. Use when a developer wants a fixed-id document (settings, navigation, footer) edited in place, hidden from the default content list, with no "create new" or "duplicate" affordances — or when migrating a userland singleton implementation or a third-party singleton plugin (e.g. sanity-plugin-singleton-management) to the first-class API. --- # Sanity Singletons A "singleton" is a document with a fixed id that can be created exactly once. Common examples: site settings, navigation, footer content. Studio supports singletons as a first-class primitive via the `document.singletons` configuration registry plus a small set of Structure Tool helpers. **Requires `sanity` 6.17.0 or later.** Check the installed version in the lockfile before using this API. On older Studios, either upgrade first or use the userland pattern (fixed `documentId` in a custom structure, plus manual `newDocumentOptions` and `duplicate` filtering) described in `sanity-best-practices` → `studio-structure`. ## When to use this skill - A developer asks how to create a "settings document" or "singleton". - A studio configuration needs a `document.singletons` registry entry. - Structure Tool needs to render a singleton as a list item or document pane. - You're migrating an existing userland singleton implementation to the first-class API. - You're migrating from a third-party singleton plugin such as `sanity-plugin-singleton-management` (or its predecessor `sanity-plugin-singleton-tools`). ## Registering a singleton Singletons are registered in configuration, **not** on the schema type. A singleton definition binds a _definition id_ to a _document id_ and a _schema type_: ```ts import {defineConfig, defineSingleton} from 'sanity' export default defineConfig({ schema: { types: [/* siteSettings and campaign are ordinary document types */], }, document: { singletons: [ // String shorthand — expands to // {id: 'siteSettings', documentId: 'siteSettings', schemaType: 'siteSettings'} 'siteSettings', // Definition object. `defineSingleton` is an optional typed identity // helper; a plain object literal works too. `id` is omitted here, so it // inherits each `documentId`. defineSingleton({ documentId: 'springCampaign', schemaType: 'campaign', title: 'Spring campaign', // optional display metadata initialValue: {season: 'spring'}, // optional per-singleton initial value }), defineSingleton({ documentId: 'summerCampaign', schemaType: 'campaign', title: 'Summer campaign', initialValue: {season: 'summer'}, }), ], }, }) ``` Key facts: - **`defineSingleton` produces a singleton _definition_, not a document schema.** The schema type it references is defined separately with `defineType` and needs no singleton-specific configuration. - **Multiple singletons may share a schema type** (like the two campaigns above), each with its own `title`, `icon`, and `initialValue` (falling back to the schema type's), and a shared schema type may also back ordinary documents. - **The definition id is the singleton's stable identity**, and it is **optional** — it inherits `documentId` when omitted. Structure code references it (`S.listItem().singleton('springCampaign')`). Set it explicitly only to be verbose, to guard against future collisions, or to address a singleton universally when different workspaces or environments map it to different document ids. - A resolver function is also accepted: `singletons: (prev, context) => [...prev, ...]`. Resolvers only ever receive fully resolved definitions (string shorthands are expanded first). Validation at config-resolution time (all failures aggregate into one `ConfigResolutionError`): - `id`: non-empty, unique across definitions (inherited ids count — an explicit id may not collide with another definition's inherited one). Used verbatim as a Structure Tool node id, so it is limited to `[a-zA-Z0-9._-]` and may not start with `__edit__`. It also may not match the name of a document type that no singleton claims, since the default content list keys both by id (the string shorthand never trips this — the type it names is claimed by the definition itself). - `documentId`: non-empty, unique, published-id shaped (no `drafts.` / `versions.` prefix, only `[a-zA-Z0-9._-]`). - `schemaType`: must name an existing document type. Need not be unique. - Templates: an untagged template must not reuse a definition id (the generated singleton template claims it); at most one template may carry a given `singleton` tag; tags must reference registered definitions. ## What Studio does automatically 1. **Generates a dedicated initial value template per singleton** — tagged with the definition id via `ResolvedTemplate.singleton`, value from `definition.initialValue ?? schemaType.initialValue` — instead of the plain per-type template, and **removes tagged templates from every "create new" surface** (global create menu, structure panes, reference inputs). The tagged template stays in `source.templates`, so opening the singleton before it exists still applies its initial value. 2. **Injects `context.singleton`** (the definition id) into document-scoped configuration contexts — `document.actions`, `badges`, `inspectors`, field actions, `comments.enabled`, `askToEdit.enabled` — looked up by _published_ document id, so drafts and release versions of the singleton match, however the document was opened (structure, intent, deep link, search). 3. **Filters the `duplicate` document action**, after all user resolvers run, so it cannot be reintroduced via `document.actions`. 4. **Hides the schema type from the implicit default content list** in Structure Tool, and **appends the singleton itself to that list** — one item per definition, after the document type lists, in registration order, each equivalent to `S.listItem().singleton(id)`. A studio that has not configured Structure Tool needs no structure code at all. This applies only to the default structure; a `structure` resolver replaces it wholesale. What Studio deliberately does **not** do: - **Delete, unpublish, and discard stay available.** Deleting a singleton is a legitimate "reset": structure still points at the fixed id, and editing recreates the document. To hide delete as well: `document: {actions: (prev, context) => (context.singleton ? prev.filter((action) => action.action !== 'delete') : prev)}`. - **Explicit structure is never filtered.** `S.documentTypeList(typeName)` works for singleton schema types and intentionally lists the singleton documents alongside ordinary ones. - **No warning for "dangling" singletons.** Structure resolves lazily, so Studio cannot detect a registered singleton that a _custom_ structure never adds. (The default structure adds them all, so this only affects studios with a `structure` resolver.) Any heuristic short of eager resolution would misfire, because manual `S.document().documentId(...).schemaType(...)` wiring is supported. In a custom structure, always pair a registry entry with a structure entry. ## Surfacing singletons in Structure Tool **With the default structure there is nothing to do** — registered singletons are appended to the top-level content list automatically. In a **custom structure** (any studio passing a `structure` resolver to `structureTool()`), add them explicitly. All helpers are keyed by **definition id** and throw a `SerializeError` for unknown ids. Watch for this trap: `S.documentTypeListItems()`, the usual way to reproduce the default lists inside a custom structure, excludes singleton schema types and does **not** add singleton items. `S.list().items([...S.documentTypeListItems()])` therefore drops every singleton. Use `.singletons()` alongside it: ```ts S.list().id('__root__').title('Content').items(S.documentTypeListItems()).singletons() ``` ```ts // 1. Highest level: a list of singletons — a given set, or all of them. S.list().id('singletons').title('Singletons').singletons(['siteSettings', 'springCampaign']) S.list().id('singletons').title('Singletons').singletons() // 2. A single list item (title/icon default from the definition, then the schema type). S.listItem().singleton('siteSettings') // 3. Low level: just the document pane. S.listItem().title('Settings').id('settings').child(S.document().singleton('siteSettings')) ``` Composition rules: - Every default is overridable by normal chaining: `S.listItem().singleton('siteSettings').title('Global settings')`, `S.document().singleton('siteSettings').documentId('override')`. - **Titles are not disambiguated for you.** The list item id defaults to the definition id (unique by construction), but the title falls back to the schema type's, so singletons sharing a schema type share a label. Give each definition a `title` — it applies everywhere the singleton is rendered, including `S.list().singletons()`, which has no per-item overrides. - `S.document().singleton()` pins the singleton's tagged initial value template so its initial value applies even when the type has several templates; override with `.initialValueTemplate(...)`. - **`S.list().singletons()` returns a builder without `.items()`.** Calling `.items()` afterwards would replace the whole array and silently drop the singleton items, so the type forbids it. Call `.items([...])` _before_ `.singletons([...])`, or put `S.listItem().singleton()` entries inside a regular `.items()` array. Repeated `.singletons()` calls append. - **`singletons()` with no argument means every registered definition** (registration order, including plugin-registered ones); `singletons([])` means none. Combining it with a hand-written `S.listItem().singleton(id)` in the same list adds that singleton twice and fails with a duplicate-id `SerializeError` — pass an explicit array when mixing. - **`S.documentListItem().singleton(id)`** renders a live document preview instead of a static title, and defaults its id to the definition's `documentId` (not the definition id), because a document list item's id _is_ the document it previews. Prefer plain `S.listItem()` when the singleton document may not exist yet. ## Shared schema types and the "create new" escape hatch Declaring a singleton over schema type `T` replaces `T`'s plain per-type template with the singleton's tagged template, so `T` disappears from create menus. If ordinary `T` documents should stay creatable, define an explicit untagged template — any id works, including `T` itself, since the plain template no longer exists: ```ts schema: { templates: (prev) => [ ...prev, {id: 'campaign-non-singleton', title: 'Campaign', schemaType: 'campaign', value: {}}, ], }, ``` This is the one place the default structure is not enough on its own: it surfaces the singletons over the shared type, but the type stays filtered, so ordinary documents of it remain unlisted while the structure _looks_ complete. A shared schema type always needs an explicit `S.documentTypeListItem(typeName)` somewhere in the structure. (A future `allowNonSingletonDocuments` flag on the definition will replace both the escape-hatch template and this structure entry.) The `singleton` tag carries the semantics: templates with it are never create options; templates without it always are. The tag lives on `ResolvedTemplate` — the resolved shape in `source.templates` — not on the authoring `Template` type, so developers never set it directly. To customise a singleton's initial value via `schema.templates`, find the singleton's template by id (equal to the definition id) and spread it (`{...template, value}`) — the spread preserves the tag at runtime, keeping it out of create menus. (Setting `initialValue` on the definition itself is usually simpler.) ## Reading singletons from plugins - The resolved registry is available at `source.document.singletons` (`useSource().document.singletons`). - Document-scoped resolvers receive `context.singleton` (the definition id; `documentId` and `schemaType` are already on the context). ## Migrating a userland singleton setup Typical userland implementations combine three pieces; each is subsumed by the registry: | Userland technique | First-class replacement | | ---------------------------------------------------------------- | --------------------------------------------------------------- | | `document.newDocumentOptions` filtering out the type | Automatic (tagged singleton templates are never create options) | | `document.actions` filtering `duplicate` | Automatic (terminal, non-bypassable) | | Custom structure with `S.document().schemaType(x).documentId(y)` | Keep, or simplify to `S.listItem().singleton(id)` | Migration steps: 1. Add the singleton to `document.singletons` (string shorthand when id, document id, and type name are all identical). 2. Delete the manual `newDocumentOptions` and `duplicate` filtering for that type. 3. Replace the manual structure wiring with `S.listItem().singleton(id)` (or keep the manual wiring — it remains fully supported; ensure the `documentId`/`schemaType` pair matches the definition so `context.singleton` resolves). If the only reason a custom structure existed was to surface the singletons, delete the resolver entirely and let the default structure do it. 4. If the schema type is _only_ used by the singleton, nothing else changes. If it's shared with ordinary documents, add an explicit untagged template to keep them creatable, and `S.documentTypeList(typeName)` to keep them listed. ## Migrating from `sanity-plugin-singleton-management` [`sanity-plugin-singleton-management`](https://github.com/rcmaples/sanity-plugin-singleton-management) (a maintained fork of `sanity-plugin-singleton-tools`, with an identical API) marks schema types with `options: {singleton: true}`, registers a `singletonTools()` plugin that filters new-document options and document actions, and ships three structure helpers. Every piece maps directly onto the first-class API: | Plugin technique | First-class replacement | | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `options: {singleton: true}` on the schema type | A `document.singletons` entry (delete the schema option — it has no first-class meaning) | | `singletonTools()` plugin in `plugins: [...]` | Delete (creation and duplicate prevention are automatic) | | `singletonDocumentListItem({S, context, type, title, id, icon})` | `S.listItem().singleton(<definition id>)` (title/icon defaults come from the definition, then the schema type) | | `singletonDocumentListItems({S, context})` | `S.list().singletons()` (or nothing at all, if using the default structure) | | `filteredDocumentListItems({S, context})` | `...S.documentTypeListItems()` — singleton schema types are excluded automatically | **Document id compatibility (the critical detail):** the plugin's document id defaults to the schema type name (`S.document().schemaType(type).id(id ?? type)`), so a plugin singleton `mySingleton` edits the document `mySingleton`. The string shorthand (`singletons: ['mySingleton']`) produces exactly that document id — existing content keeps working with no data migration. If the plugin call passed an explicit `id`, carry it over as the definition's `documentId`. Migration steps: 1. For each schema type with `options: {singleton: true}`: remove the option, and register the type in `document.singletons` — the string shorthand when the plugin used the default id, otherwise `{documentId: <the explicit id>, schemaType: <type>}`. 2. Remove `singletonTools()` from `plugins` and uninstall the package. 3. Replace the structure helpers per the table above. The plugin passed `{S, context}` around; the first-class helpers need neither — they read the registry from the builder's own context. 4. Note a deliberate behavioural difference: the plugin **allowlists** actions (`publish`, `discardChanges`, `restore`), hiding delete and unpublish. The first-class API only removes `duplicate` — deleting a singleton is a legitimate "reset". To preserve the plugin's stricter behaviour, add: ```ts document: { actions: (prev, context) => context.singleton ? prev.filter(({action}) => ['publish', 'discardChanges', 'restore'].includes(action as string), ) : prev, }, ``` Only add this if the stricter behaviour is genuinely wanted — otherwise prefer the first-class default. 5. If the plugin's `singletonDocumentListItem` was used to render **multiple singletons of the same schema type** (its `title`/`id` overrides), register one definition per document id — `{documentId, schemaType, title}` — which is the first-class model for exactly that case. ## Reference Source lives in the [`sanity-io/sanity`](https://github.com/sanity-io/sanity) monorepo: - Config types & validation: [`core/config/types.ts`](https://github.com/sanity-io/sanity/blob/main/packages/sanity/src/core/config/types.ts), [`core/config/prepareConfig.tsx`](https://github.com/sanity-io/sanity/blob/main/packages/sanity/src/core/config/prepareConfig.tsx) - Structure helpers: [`Document.ts`](https://github.com/sanity-io/sanity/blob/main/packages/sanity/src/structure/structureBuilder/Document.ts), [`ListItem.ts`](https://github.com/sanity-io/sanity/blob/main/packages/sanity/src/structure/structureBuilder/ListItem.ts), [`List.ts`](https://github.com/sanity-io/sanity/blob/main/packages/sanity/src/structure/structureBuilder/List.ts) - Working example: [`dev/test-studio/schema/singletons.ts`](https://github.com/sanity-io/sanity/blob/main/dev/test-studio/schema/singletons.ts), [`dev/test-studio/structure/resolveSingletons.ts`](https://github.com/sanity-io/sanity/blob/main/dev/test-studio/structure/resolveSingletons.ts), [`dev/test-studio/structure/resolveStructure.ts`](https://github.com/sanity-io/sanity/blob/main/dev/test-studio/structure/resolveStructure.ts) - Worked migration of userland singletons over _shared_ schema types (escape-hatch templates in [`dev/test-studio/initialValueTemplates/index.ts`](https://github.com/sanity-io/sanity/blob/main/dev/test-studio/initialValueTemplates/index.ts), explicit `S.documentTypeListItem()` opt-back-ins): the `circular`, `grrm`, and `jrr-tolkien` definitions in `resolveSingletons.ts`Original on GitHubsanity-studio-upgradeProduces a tailored Sanity Studio upgrade plan by inspecting the repository's installed versions, config, and source, then reporting only the breaking changes that actually apply. Covers Studio v3 and later; v2 projects are identified and redirected, not planned. Use this skill whenever someone wants to upgrade, migrate, or modernize a Sanity Studio across one or more major versions from v3 onward, asks what will break if they bump the `sanity` package, asks why their Studio broke after an upgrade, or asks how far behind their Studio is. Triggers on "upgrade sanity studio", "migrate our studio to v6", "bump sanity", "what breaks if we upgrade", "our studio is on an old version", "sanity upgrade plan", "is our studio out of date", "we are several majors behind". DO NOT load for upgrading non-Sanity dependencies, for Content Lake `apiVersion` questions, for content or schema migrations that change documents, or for setting up a new Sanity project.ReadClose
--- name: sanity-studio-upgrade description: Produces a tailored Sanity Studio upgrade plan by inspecting the repository's installed versions, config, and source, then reporting only the breaking changes that actually apply. Covers Studio v3 and later; v2 projects are identified and redirected, not planned. Use this skill whenever someone wants to upgrade, migrate, or modernize a Sanity Studio across one or more major versions from v3 onward, asks what will break if they bump the `sanity` package, asks why their Studio broke after an upgrade, or asks how far behind their Studio is. Triggers on "upgrade sanity studio", "migrate our studio to v6", "bump sanity", "what breaks if we upgrade", "our studio is on an old version", "sanity upgrade plan", "is our studio out of date", "we are several majors behind". DO NOT load for upgrading non-Sanity dependencies, for Content Lake `apiVersion` questions, for content or schema migrations that change documents, or for setting up a new Sanity project. compatibility: Requires network access to the npm registry and sanity.io docs for version and changelog lookups --- # Sanity Studio upgrade planner Generate an upgrade plan for the Sanity Studio in the current repository. The plan's value is **subtraction**. A list of every breaking change between two versions already exists; it is called the changelog, and it is not useful to someone mid-upgrade. This skill produces the much shorter list of changes that apply to *this* repository, plus the questions only a human can answer. ## Three rules that determine whether the output is trustworthy **1. Never state a version number from memory. Look it up, and confirm it exists.** Package versions change weekly. Every version in the report must come from either the repository's lockfile (for current state) or a live registry query (for targets). If a lookup is not possible, say so in the report rather than guessing. A plan that names a stale "latest" is worse than no plan, because the reader will act on it. There is a second, worse version of this failure: a version number that was never published at all, arrived at by assuming one package tracks another's numbering. That one fails at install. Any version you are about to describe as "lockstep" or "matches core" needs an existence check first. The same applies to API names. An export, an import subpath, or a function signature recalled from memory is a guess, and it is a guess the reader will paste into their editor. Read it from the package's README or `exports` map, or mark it with an inline `// VERIFY:` comment **at the snippet itself**. See section 6 of `plugins.md` and section 8 of `report-template.md`. **2. Read and report. Never modify.** Inspect files, run read-only shell commands, query registries. Do not edit `package.json`, config files, or source. The reader decides what to change; a planner that edits code will be turned off. If the user explicitly asks you to perform the upgrade afterward, that is a separate task they have consented to. **Where the line actually falls**, because a vague version of this rule makes an agent hesitate over commands that are fine: - **Never**: writing to any file in the repository, installing into it, or mutating a lockfile. `pnpm install`, `npm install`, `npm ci` and `npx` without `--no-install` are all out. - **Fine**: reading files, and network reads such as `npm view`, a changelog fetch, or `npm pack` **into a temporary directory outside the repository** that you then delete. - **Recommended to the reader, not run by you**: `pnpm install --lockfile-only` is how a dependency prediction gets settled. It belongs in the report as a command for them to run, with what to expect from it. Do not run it yourself, because it rewrites their lockfile. The one place this skill writes anything is unpacking a tarball to inspect type declarations, and section 6 of `plugins.md` shows how to keep that outside the project. **3. Separate what you verified from what you inferred.** Every finding lands in one of three buckets: confirmed applicable (you found the condition in the repo), needs a human answer (you cannot determine it from code), or not applicable (omit it entirely). Never pad the report with items you could not check. An honest short report beats a comprehensive-looking one. One consequence is easy to miss and worth stating outright: **a read-only planner has no dependency resolver, so it cannot know what a tree will contain after a change.** Predictions about deduplication belong in the report as expectations with the verification command attached, never as findings. See `package-coupling.md`. ## The verification rules, in one place These are referred to by number throughout the reference files, so they are stated once here rather than restated in each. Everything above is R1 to R4; the rest are the specific ways those go wrong. | | Rule | Where it bites | | --- | --- | --- | | **R1** | Never state a version from memory. Take current state from the lockfile, targets from a live registry query. | `version-lookup.md` §1 | | **R2** | Read and report. Nothing in the repository changes, nothing is installed, no lockfile is mutated. | Above, and `plugins.md` §6 | | **R3** | Separate verified from inferred. Never assert what a dependency tree will contain after a change; a planner has no resolver. | `package-coupling.md` §6, `plugins.md` §5 | | **R4** | Confirm every recommended version was actually published before it goes in the report. | `version-lookup.md` §3 | | **R5** | Every "X requires Y" names the manifest it was read from, at the version being installed at that stop. Requirements do not carry backwards across majors. | `version-lookup.md` §6 | | **R6** | Evaluate a version range, never read it. Anything with a `\|\|`, a `<`, or two comparators in one clause goes through `semver.satisfies` first. | `version-lookup.md` §6 | | **R7** | A name in an export list is not a working export. Check its declared type and any `@deprecated` tag; `never` means removed. | `plugins.md` §6 | R6 and R7 exist because both have already produced confident, wrong, specific advice: a Node version reported as unsupported when it was fine, and a required code edit filed under "already satisfied". They are cheap to run and they fail silently when skipped. ## Scope: v3 and later This skill plans upgrades from Studio v3 onward. **Studio v2 is out of scope and is a hard stop.** The reason is not that v2 is hard. It is that v2 to v3 is a rewrite of the Studio's configuration and plugin layer rather than a dependency upgrade: the config format changed, the "parts" system that v2 plugins and overrides were built on no longer exists, packages were consolidated, and much of the v2-era plugin ecosystem was never ported. A generated plan for that boundary would be a list of confident-sounding specifics that this skill cannot verify, handed to someone about to spend weeks on the work. That is the worst possible output. **If you detect v2, stop and report** rather than planning. Step 1 covers detection and what to say. Do not write a plan file for a v2 project. ## Procedure ### Step 1: Establish ground truth, and check the version floor Read `references/detect.md` and follow it. It lists the files to read, the commands to run, and the facts to record. The single most common mistake is reading versions from `package.json`. Caret ranges are not installed versions. Get the resolved version from the lockfile. The second most common mistake is reading them from the wrong lockfile. A repository can contain several installs that disagree, so decide which tree the plan is for, take every version fact from that tree, and name it in the report header. If there is no Sanity Studio in this repository, say so and stop. **Then check the floor before doing anything else.** If the resolved `sanity` major is below 3, or there is no `sanity` package and the project depends on v2-era packages such as `@sanity/base` or `@sanity/desk-tool`, or there is a `sanity.json` and no `sanity.config.*`, this is a v2 project. Stop there and tell the reader: 1. What you detected, and the evidence for it 2. That this skill covers v3 and later, and why v2 to v3 is a different kind of project: a rewrite of the configuration and plugin layer, not a version bump 3. That the right starting point is the official v2 to v3 migration guide, which they should find on the Sanity docs site rather than take from you second-hand 4. That every v2-era plugin needs its own compatibility check, since many were never ported 5. That once they are on v3, running this skill again will plan the rest of the span, which is a much smaller job Be useful about it. A hard stop that explains itself and points somewhere is a good answer; a refusal is not. But do not soften it into a partial plan, and do not estimate the v2 to v3 work. If both `sanity.json` and `sanity.config.*` are present, treat the resolved `sanity` version as authoritative. A leftover `sanity.json` in an otherwise v3+ project is worth mentioning as cleanup, not a reason to stop. ### Step 2: Determine the span You need two versions: **from** (resolved, installed) and **to** (the target). Read `references/version-lookup.md` for how to query current versions and changelogs authoritatively. **The target is `latest`.** Recommend it and give the reasoning. Landing short means doing the whole job and still being behind, and more importantly, current plugin versions track current core, so an older core with current plugins often produces a worse dependency tree than the newest release does. Report the target's publish date and a one-line fallback so the reader can apply constraints you cannot see, but that is disclosure, not a hedge, and it does not change the recommendation. Deviate only for a constraint the reader has actually stated, and then give the pin a review date. State the span explicitly in the report. A v3 project and a v5.31 project are completely different jobs and the reader needs to know which one they have. ### Step 3: Load only the boundaries you cross Read `references/boundaries.md` first. It is a short index: the coverage bounds, the two-edge fetch rule, and a table saying which boundary files the span needs. **Then read only those files.** Boundary content is split one file per major, so a span that crosses one boundary loads one file rather than all of them. A project on 5.31 crossing into v6 reads the index, `boundary.v6.md` and `deprecations.md`, and nothing else: the v4 and v5 files would cost context and invite findings that do not apply. Each `boundary.v*.md` holds the crossing *into* that major plus the undeclared changes *inside* that major's line, because a span that crosses a boundary lands somewhere in the line above it and needs both. Then read `references/package-coupling.md`. It applies to every span. ### Step 4: Fetch what the references do not cover `references/boundaries.md` declares **two** bounds on its within-line coverage, and both need respecting. Fetch the changelog for any part of the span that falls **above the upper bound** or **below the lower bound**. A project starting below the lower bound needs two fetches: from its current version up to that bound, and from the upper bound to the target. The curated middle is used as-is. The lower bound matters as much as the upper one, and it fails more quietly. Without it you will trust the file for a range it never examined and report that nothing there applies, which reads as a verified finding and is actually an unexamined gap. **Never state that a range is clean unless it sits inside the declared bounds or you fetched it yourself and got real content back.** That last clause is not padding. Below the lower bound the upstream changelog does not exist at all, so the fetch returns almost nothing, and **an empty fetch is not a clean range.** `boundaries.md` says which range this affects and what to report instead. Reporting silence as "nothing applies" there is the single easiest way for this skill to produce a confident lie. Pay particular attention to breaking changes that shipped in **minor** releases without being labelled as breaking. Those are the ones that surprise people, because nobody reads minor release notes across forty releases. The references list known examples; assume more exist. ### Step 5: Test applicability For each candidate change, find the condition in the repository. If you cannot determine it from code, it goes in the human questions section, not in the findings. Examples of the difference: - "Custom auth providers now replace built-ins instead of appending" → grep the config for an `auth` block. Present or absent. **Determinable.** - "Default search strategy changed, results will shift" → whether that matters depends on how editors search. **Not determinable. Ask.** Prefer conditions you can actually evaluate. `grep -r "data-slate"` is a real test. "Do you have complex custom components?" is not. ### Step 6: Resolve the dependency graph Apply `references/package-coupling.md`. This is where most upgrades actually break, and it is the part a changelog cannot tell you, because it depends on which packages this project happens to depend on directly. The rule that matters most: for any `@sanity/*` package the project depends on **directly**, check what version the *target* `sanity` release depends on and match that, rather than taking the package's own `latest`. Taking `latest` for a shared package like `@sanity/ui` puts two majors of it in one dependency tree, which produces duplicate-context errors and unstyled components that look like unrelated bugs. ### Step 6b: Assess plugins Read `references/plugins.md` and follow it whenever the project has any plugin, which is nearly always. Plugins block more upgrades than the Studio itself does, so they get their own pass and their own section in the report. Three things to carry into it: verify every plugin's compatibility rather than assuming it from who publishes it; let ownership decide the *path* once something is incompatible, not the verdict; and verify the *API shape* of any snippet you write against the package, separately from verifying its version, because a compatible version can still have renamed the export you are about to recommend. ### Step 7: Write the report Follow `references/report-template.md` exactly. Write it to `SANITY-UPGRADE-PLAN.md` in the repository root unless the user names a different path. Write a file rather than only printing to the terminal. The plan usually needs to reach people who are not at this keyboard: a lead, a reviewer, a support engineer. A file can go into a pull request or be pasted into a thread; terminal output cannot. ## Judgment calls worth making explicitly **Recommend a sequence, not a single jump.** Crossing several majors in one commit makes failures impossible to attribute. Suggest intermediate stops at the last release of each major, and say why: it isolates each set of changes. But a stop is only real if it is reachable. Each one needs its plugin versions resolved, because a plugin peering only recent majors can make an intermediate stop impossible to install. If you cannot resolve a stop, label it provisional rather than presenting the sequence as validated. Fewer verified stops beat more hypothetical ones. **When you drop a stop, name what it costs.** Skipping one is often right: a boundary whose only applicable change is a Node floor is not worth a commit of its own, and a stop that cannot be reached without a forced duplicate major is worse than no stop. But the resulting hop then crosses two boundaries at once, and that is the exact thing the sequence exists to prevent. A plan that shows the evidence for skipping and stays silent on the consequence reads as though the trade were free. So say both halves: why the stop was dropped, and that a failure in the combined hop could originate at either boundary, so debugging it means bisecting rather than reading the plan. One sentence covers it. The reader can accept the trade once they can see it. **Size the work honestly.** If the project has two files importing `@sanity/ui` and no custom auth, say the upgrade is small. Inflating scope to look thorough wastes the reader's week. Equally, if the project imports from `sanity/_internal` or has a large custom component surface, say the upgrade is substantial rather than producing a plan that makes hard work look easy. **Make the plan survive being skimmed.** It will be. A multi-boundary plan runs to several thousand words, and the person reading it is about to spend a week on the work, not an afternoon studying the document. So the top of the plan carries the whole thing in one screen, everything below it is reference to be read as the work reaches it, and findings are grouped by what the reader has to do rather than by which release the change came from. The specific failure to design against: a change that fails silently, sitting in a uniform table between two cosmetic ones, at identical visual weight. Length is not the enemy; flat weighting is. **Write for the engineer who has to do the work, and describe the tree rather than the team.** This plan is usually read by someone at the customer, often someone who did not make the decisions that produced the current state. Keep the evidence, the specificity and the severity exactly as strong as the facts support: softening a real blocker or a real cost is a disservice, and an engineer can tell. What to drop is the implied verdict. "The deploy pipeline builds from the caret ranges rather than the lockfile" and "whoever set this up got it wrong" contain the same finding, and only one of them gets acted on. Reserve "you" for what to do next. Stay inside the upgrade, too: an unused dependency is not an upgrade finding, and a plan that drifts into general code review spends the reader's attention on things that do not gate the work. **Name what you could not see.** Monorepos hide things: a `tsconfig.json` that extends a base file outside the repository, a workspace root that hoists React, a CI config in another directory. If a fact you needed was out of reach, put it in the human questions section by name. "I could not read `moduleResolution` because your tsconfig extends a file outside this repo" is useful. Silently omitting it is not. **Do not promise roadmaps.** If asked whether a deprecated API will return or be removed, describe its current documented state and stop. Never speculate about future releases. ## Reference files | File | Read when | | --- | --- | | `references/detect.md` | Always, at step 1 | | `references/version-lookup.md` | Always, at step 2 and step 4 | | `references/boundaries.md` | Always, at step 3. Index: coverage bounds and which boundary files to read | | `references/boundary.v4.md` | Step 3, if the span crosses into or sits in v4 | | `references/boundary.v5.md` | Step 3, if the span crosses into or sits in v5 | | `references/boundary.v6.md` | Step 3, if the span crosses into or sits in v6 | | `references/deprecations.md` | Step 3, always. Short, and not tied to a boundary | | `references/package-coupling.md` | Always, at step 6 | | `references/plugins.md` | Step 6b, whenever the project has plugins | | `references/report-template.md` | Step 7 |
Original on GitHubseo-aeo-best-practicesSEO and AEO best practices for metadata, Open Graph, sitemaps, robots.txt, hreflang, JSON-LD structured data, EEAT, and content optimized for search engines and AI answer surfaces. Use this skill when implementing page SEO, technical SEO, schema markup, international SEO, AI-overview readiness, or improving content for Google, ChatGPT, Perplexity, and similar assistants.ReadClose
--- name: seo-aeo-best-practices description: SEO and AEO best practices for metadata, Open Graph, sitemaps, robots.txt, hreflang, JSON-LD structured data, EEAT, and content optimized for search engines and AI answer surfaces. Use this skill when implementing page SEO, technical SEO, schema markup, international SEO, AI-overview readiness, or improving content for Google, ChatGPT, Perplexity, and similar assistants. --- # SEO & AEO Best Practices Principles for optimizing content for both traditional search engines (SEO) and AI-powered answer engines (AEO). Includes Google's EEAT guidelines and structured data implementation. ## When to Apply Reference these guidelines when: - Implementing metadata and Open Graph tags - Creating sitemaps and robots.txt - Adding JSON-LD structured data - Optimizing content for featured snippets - Preparing content for AI assistants (ChatGPT, Perplexity, etc.) - Evaluating content quality using EEAT principles ## Core Concepts ### SEO (Search Engine Optimization) Optimizing content to rank well in traditional search results (Google, Bing). ### AEO (Answer Engine Optimization) Optimizing content to be selected as authoritative answers by AI systems. ### EEAT (Experience, Expertise, Authoritativeness, Trustworthiness) Google's framework for evaluating content quality. ## References Start with the one reference that matches the task, such as technical SEO, structured data, EEAT, or AI-answer readiness. See `references/` for detailed guidance: - `references/eeat-principles.md` — EEAT implementation and author schema - `references/structured-data.md` — JSON-LD patterns (Article, FAQ, Breadcrumb, Product) - `references/technical-seo.md` — Technical SEO checklist (metadata, sitemaps, hreflang, robots.txt) - `references/aeo-considerations.md` — AI/AEO considerations (AI Overviews, crawler management)
Original on GitHub
Author and licence
These skills were written and published by Sanity at github.com/sanity-io/agent-toolkit under the MIT licence. skillsmcp copies them unchanged, checks the repository once a day, and is not affiliated with Sanity. A skill is a set of instructions an AI agent may follow, so read a skill before you let an agent use it.
Show the licence
MIT License Copyright (c) 2025 Sanity Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.