DocsIntegrations (experimental)

Sanity (experimental)

@generic-translation/sanity - a Studio plugin and server helper that translate Sanity documents through Generic Translation. Experimental and unverified against a real Sanity project.

On this page

Experimental. Unverified against a real Sanity project. @generic-translation/sanity was built without access to a Sanity project or a running Studio. Everything that touches Sanity was tested against an in-memory fake of the client methods used, written from the documented client API. Only the Generic Translation half was exercised live. Details are in Status.

Source: generic-translation-integrations/sanity. Not on npm yet; link it from a checkout until the @generic-translation/* packages are published.

It offers a Studio plugin (a “Translate with Generic Translation” document action and a “Generic Translation” status tool), a framework-free core (@generic-translation/sanity/core) that walks a document against its schema, and a server helper (@generic-translation/sanity/server). Both i18n models are supported: document-level (translated sibling documents) and field-level ({ en, es } objects and internationalizedArray).

Quickstart

Once the package is available to your project (npm install @generic-translation/sanity @generic-translation/core; peer dependencies for the Studio entry are sanity@^6, @sanity/ui@^4 and react, and only sanity@6.25 was used for type-checking):

// sanity.config.ts
import { defineConfig } from "sanity";
import { genericTranslationTranslate } from "@generic-translation/sanity";

export default defineConfig({
  plugins: [
    genericTranslationTranslate({
      sourceLocale: "en",
      locales: ["es", "fr", { id: "ja", title: "Japanese" }],
      model: "document", // or "field"
      layout: "metadata", // document model: also keep translation.metadata documents
      documentTypes: ["article", "page"],
    }),
  ],
});

Open a document, choose Translate with Generic Translation in the document actions menu, tick locales and run. Translations are written as drafts unless publish: true, and existing translations are not overwritten unless you tick Overwrite existing. The Generic Translation tool in the top bar shows a badge per locale for every document and a Translate missing button.

From a script or webhook

import { createClient } from "@sanity/client";
import { GenericTranslation } from "@generic-translation/core";
import { translateDocument } from "@generic-translation/sanity/server";

const sanity = createClient({ projectId, dataset, apiVersion: "2025-02-19", token: process.env.SANITY_TOKEN, useCdn: false });
const genericTranslation = new GenericTranslation({ apiKey: process.env.GENERIC_TRANSLATION_API_KEY });

const result = await translateDocument(sanity, "article-123", {
  locales: ["es", "fr"],
  sourceLocale: "en",
  model: "document",
  genericTranslation,
});
// result.results: [{ locale, status: "created" | "updated" | "skipped" | "failed", documentId, units, warnings, error? }]

Pass schema (the compiled schema, or schemaFromTypes([...])) for exact field rules; without it a heuristic walk is used.

Reference

Plugin options

Option Default Meaning
locales required Target locales: "es" or { id, title }.
sourceLocale "en" Locale the content is written in.
model "document" "document" or "field".
layout "metadata" Document model: "metadata" or "sibling".
languageField "language" Language field on translated documents; must exist in the schema.
documentTypes all non-system types Types that get the action and appear in the tool.
skipFields [] Field names never translated.
publish false Write published documents instead of drafts.
apiVersion 2025-02-19 Studio client API version.
genericTranslation.projectId, genericTranslation.baseUrl Override project and API URL.
genericTranslation.secretsNamespace "generic-translation" The secrets document is secrets.<namespace>.
genericTranslation.proxy { url, headers? }: send requests through your own proxy.
genericTranslation.apiKey Hard-coded key, local development only.

Where the API key lives

A Studio is a browser app, so anything it can use, an editor’s browser can read. In order of increasing exposure:

  1. Proxy (genericTranslation.proxy), recommended for production. The Studio calls your server, which authenticates the editor and forwards the request to Generic Translation with the real Authorization header. The key never reaches a browser. The plugin does not ship a proxy; you run a small server or edge function.
  2. Sanity secrets document (default). The key is stored in the private document secrets.<namespace>. It is not in your bundle or repo, but any Studio user with dataset read access can read it and it is used from their browser. Give it only translations:generate, use one key per Studio, and rotate it when people leave.
  3. genericTranslation.apiKey in the config ends up in the public Studio bundle. Local development only.

Headless use (translateDocument) reads the key from your environment; nothing reaches a browser.

What gets translated

With a schema: string and text fields, strings in arrays, nested objects and array-of-object members, image alt/caption and other custom fields on image/file, and Portable Text blocks and custom block types (including inline objects’ string fields).

Not translated: slug, reference, url, email, date, datetime, number, boolean, geopoint, asset/hotspot/crop, fields with options.list, fields not in the schema, the language field, system fields (_id, _type, _key), and strings that are only URLs, dates or emails or contain no letters. Opt a field out with options: { genericTranslation: { translate: false } }, or a list field back in with translate: true.

Without a schema, a conservative heuristic skips slugs, references, assets, keys such as href/url/id/language, and non-prose strings.

Portable Text

A block becomes one message. Each mark run is a numbered tag in document order and inline objects are self-closing tags, for example Read the <0>docs</0> and <1>bold<2> then bold-italic</2></1><3/> done. Link annotations (markDefs, href included), block _key, style, listItem, level, custom blocks and inline objects are preserved. Translators may reorder tags and marks follow the numbers. A translation that drops or invents tags or variables is rejected: the source text is kept and a warning is returned. Mark order inside a span may differ from the original (the set is the same). Plain strings go as opaque STRING data; each unit carries a context such as sanity article.body (Portable Text, h2).

i18n models

Document-level. For article-123 and locale es, a sibling article-123__i18n_es is written (as a drafts. document unless publish: true) with language: "es". IDs are deterministic, so re-runs update instead of duplicating. References are copied as-is, not remapped to translated documents. With layout: "metadata", a translation.metadata document is created or extended in the layout used by @sanity/document-internationalization; a translation that plugin already linked is detected and reused. Siblings and metadata are written in one transaction. Your schema needs the language field, as that plugin requires.

Field-level. Localized fields are detected from the data: internationalizedArray values, or objects whose keys are all locale codes and include the source locale ({ en: "Hello", es: "Hola" }). Only those fields are read and written. Existing target values are kept unless existing: "overwrite". The write is a single patch to the draft with ifRevisionID, so a concurrent edit makes the call fail instead of being overwritten.

Limits

  • Annotations with custom translatable fields (for example a title on a link) are kept verbatim; only inline objects and block-level fields are walked.
  • References are not remapped.
  • Draft handling assumes the default draft/publish workflow, not Content Releases or versions.
  • “Source changed” status is an approximation from _updatedAt.
  • Quota and rate limits are Generic Translation’s; messages are sent 50 per request.

Status

Exercised for real A fixture article went through the live Generic Translation API and was reassembled: Portable Text link and strong marks, markDefs, keys and the inline object survived a Spanish translation. The code type-checks against the real sanity@6.25 and @sanity/ui@4 types and the bundle builds.
Tested against mocks only Reads and writes to Sanity, through an in-memory fake of getDocuments, fetch and transaction().
Never run The React UI in a real Studio (dialog, tool, secrets form), plugin registration in a live sanity dev, GROQ against a real dataset, document permissions, draft and publish behavior on a real dataset, and interaction with the real @sanity/document-internationalization and sanity-plugin-internationalized-array plugins (the layouts follow their READMEs but were not validated by installing them).

Something wrong or unclear on this page? Open an issue.

Type to search the documentation.