focusreactive

payload plugin translator

by focusreactive
payload-plugins
Translation
v3
^3.90.0
^3.76.0 · prerelease
MIT

Overview

Summary generated from the README

Translates localized text, textarea and rich-text fields in the collections you choose, at any depth inside groups, arrays, blocks and tabs. Editors start translations from the document edit view, the collection list or a single field, and jobs run through Payload Jobs or inline. It ships an OpenAI-compatible adapter, requires Payload 3.90 or later with localization enabled, and depends on the guard plugin and an access policy.

Features

  • Translate one document, a whole collection, or several target locales in one run
  • Per-field translate control and exclusion via withFieldTranslation
  • Auto-translate on save of the source locale with optional debounce
  • Overwrite or skip-existing strategies, plus optional publish of the translated locale
  • Custom translation providers, with an OpenAI-compatible adapter included
  • Provenance tracking flags stale translations when the source changes

Use cases

  • Fill in new locales of a multi-language site without copying text by hand
  • Keep translated locales in sync automatically when the source locale is edited
  • Restrict who may translate, bulk translate or publish using role-based access policies

From the author

Translation plugin for Payload CMS 3.x. Automatically translate your localized content using any translation provider.

Installation

npm i @focus-reactive/payload-plugin-translator

37

Stars

5

Forks

33

Open Issues

Today

Last Updated

3.9k

Weekly Downloads

v0.20.1

npm Version

846.4 KB

Unpacked Size

9

Dependencies

Repository stars

37+22 since Sep 7

Show data
Repository stars by day (UTC)
DateStars
Dec 6, 202637
Dec 5, 202637
Dec 4, 202637
Dec 3, 202637
Dec 2, 202637
Dec 1, 202636
Nov 30, 202635
Nov 29, 202635
Nov 28, 202634
Nov 27, 202634
Nov 26, 202634
Nov 25, 202634
Nov 24, 202634
Nov 23, 202634
Nov 22, 202634
Nov 21, 202634
Nov 20, 202633
Nov 19, 202632
Nov 18, 202632
Nov 17, 202632
Nov 16, 202632
Nov 15, 202632
Nov 14, 202632
Nov 13, 202632
Nov 12, 202632
Nov 11, 202632
Nov 10, 202632
Nov 9, 202631
Nov 8, 202631
Nov 7, 202631
Nov 6, 202631
Nov 5, 202631
Nov 4, 202630
Nov 3, 202630
Nov 2, 202630
Nov 1, 202630
Oct 31, 202630
Oct 30, 202630
Oct 29, 202630
Oct 28, 202630
Oct 27, 202630
Oct 26, 202630
Oct 25, 202630
Oct 24, 202629
Oct 23, 202629
Oct 22, 202629
Oct 21, 202629
Oct 20, 202629
Oct 19, 202629
Oct 18, 202629
Oct 17, 202627
Oct 16, 202626
Oct 15, 202626
Oct 14, 202626
Oct 13, 202625
Oct 12, 202625
Oct 11, 202625
Oct 10, 202625
Oct 9, 202625
Oct 8, 202625
Oct 7, 202625
Oct 6, 202624
Oct 5, 202624
Oct 4, 202624
Oct 3, 202623
Oct 2, 202622
Oct 1, 202622
Sep 30, 202620
Sep 29, 202620
Sep 28, 202620
Sep 27, 202620
Sep 26, 202619
Sep 25, 202618
Sep 24, 202618
Sep 23, 202618
Sep 22, 202618
Sep 21, 202618
Sep 20, 202618
Sep 19, 202618
Sep 18, 202618
Sep 17, 202618
Sep 16, 202618
Sep 15, 202618
Sep 14, 202618
Sep 13, 202617
Sep 12, 202617
Sep 11, 202617
Sep 10, 202616
Sep 9, 202616
Sep 8, 202616
Sep 7, 202615

Shared by 15 plugins in focusreactive/payload-plugins.

npm weekly downloads

3.4K+1.8K since Sep 7

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 20263,438
Dec 5, 20263,164
Dec 4, 20262,912
Dec 3, 20262,688
Dec 2, 20262,531
Dec 1, 20261,994
Nov 30, 20262,000
Nov 29, 20261,879
Nov 28, 20261,788
Nov 27, 20261,765
Nov 26, 20261,758
Nov 25, 20261,759
Nov 24, 20261,819
Nov 23, 20261,873
Nov 22, 20261,928
Nov 21, 20261,947
Nov 20, 20261,851
Nov 19, 20261,637
Nov 18, 20261,743
Nov 17, 20261,709
Nov 16, 20261,651
Nov 15, 20261,786
Nov 14, 20261,964
Nov 13, 20261,837
Nov 12, 20261,917
Nov 11, 20261,767
Nov 10, 20261,978
Nov 9, 20262,064
Nov 8, 20261,928
Nov 7, 20261,869
Nov 6, 20262,082
Nov 5, 20262,010
Nov 4, 20262,143
Nov 3, 20261,926
Nov 2, 20262,008
Nov 1, 20262,221
Oct 31, 20262,404
Oct 30, 20262,328
Oct 29, 20262,107
Oct 28, 20261,721
Oct 27, 20261,722
Oct 26, 20261,562
Oct 25, 20261,260
Oct 24, 20261,038
Oct 23, 2026628
Oct 22, 2026870
Oct 21, 20261,298
Oct 20, 20261,286
Oct 19, 20261,259
Oct 18, 20261,298
Oct 17, 20261,291
Oct 16, 20261,539
Oct 15, 20261,573
Oct 14, 20261,660
Oct 13, 20261,651
Oct 12, 20261,700
Oct 11, 20261,985
Oct 10, 20261,966
Oct 9, 20261,986
Oct 8, 20262,136
Oct 7, 20262,073
Oct 6, 20262,111
Oct 5, 20262,431
Oct 4, 20262,242
Oct 3, 20262,197
Oct 2, 20262,082
Oct 1, 20261,878
Sep 30, 20261,575
Sep 29, 20261,578
Sep 28, 20261,211
Sep 27, 20261,070
Sep 26, 2026990
Sep 25, 20261,051
Sep 24, 20261,302
Sep 23, 20261,484
Sep 22, 20261,484
Sep 21, 20261,677
Sep 20, 20261,971
Sep 19, 20262,185
Sep 18, 20262,212
Sep 17, 20262,008
Sep 16, 20261,879
Sep 15, 20261,899
Sep 14, 20261,725
Sep 13, 20261,692
Sep 12, 20261,431
Sep 11, 20261,524
Sep 10, 20261,567
Sep 9, 20261,693
Sep 8, 20261,646
Sep 7, 20261,667

Each point is npm's rolling 7-day download count.

Health Score

71/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1177993877-payload-plugin-translator.svg)](https://payloaddirectory.dev/plugins/1177993877-payload-plugin-translator)
HTML
<a href="https://payloaddirectory.dev/plugins/1177993877-payload-plugin-translator"><img src="https://payloaddirectory.dev/badge/1177993877-payload-plugin-translator.svg" alt="Payload Directory"></a>
Updated Dec 5, 2026Created Mar 10, 2026Published Dec 4, 2026

README

Payload Translator

Translate localized Payload CMS content with an AI provider, without leaving the admin panel

Pick a source locale and one or more targets; a background job fills in every localized text, textarea and rich-text field.

npm version License: MIT

Payload localizes your content but does not translate it — an editor still copies text between locales by hand. This plugin closes that gap: every localized field gets translated, however deeply it sits inside groups, arrays, blocks and tabs, by a translation service you choose.

The plugin is built on @focus-reactive/payload-plugin-guard. Your project's access policy file decides who may translate, translate in bulk, publish translations and manage other people's jobs, and every translation reads and writes with the requesting user's own Payload rights.

Requirements: Payload ^3.90.0, @focus-reactive/payload-plugin-guard, and a config wrapped in withAccessPolicy.

AI Integration Prompt

Copy and paste this prompt into your AI assistant (Cursor, Claude, etc.) to integrate the plugin into an existing Payload project.

I want to add AI translation of localized content to my Payload CMS v3 project using
@focus-reactive/payload-plugin-translator. Follow these steps in order, and stop to ask me where a step says so.

## Rules you must follow

- Never write an access rule that admits every logged-in user: no `Boolean(req.user)`, no `() => true`,
  no `({ req }) => !!req.user`. A rule names a role, or it is `nobody`.
- Do not invent roles. Ask me which roles may do each thing listed in step 2.
- Do not add `overrideAccess: true` anywhere, and do not add `access` to the plugin's provenance collection.
- Never put an API key in code. The provider key comes from an environment variable.

## How it works

The plugin translates every localized text, textarea and rich-text field of the collections I name,
through a translation provider (an OpenAI-compatible adapter ships with it). Editors start a
translation from the document edit view, the collection list or a single field; a collection wrapped
in `withAutoTranslate` queues its own translations when its source locale is saved by an admin user.
Translations run as Payload jobs in the `translations` queue, or inline with `createSyncRunner()`.
Every translation reads the source and writes the target with the requesting user's own Payload
rights, and a queued job re-checks that user's rights when it runs.
It declares four capabilities that the project grants in its access policy:
- `translate`: translate one document or one field, see translation status, run or cancel your own jobs.
- `translateInBulk`: queue more than one document in one request, including "select all", and cancel
  your own jobs across a whole collection.
- `publish`: publish the target locale once it is translated.
- `manageJobs`: run or cancel jobs other users queued.

## Step 1: install

pnpm add @focus-reactive/payload-plugin-translator @focus-reactive/payload-plugin-guard openai

Check that `payload` is 3.90 or later; if it is not, upgrade it first.
Check that `localization` is enabled in the Payload config and that the fields to translate are
marked `localized: true`.

## Step 2: ask me about roles

Look at the auth collection named in `admin.user` and the roles it has.
Ask me: "Which roles may translate a document?", "Which roles may translate many documents at once?",
"Which roles may publish translations?" and "Which roles may run or cancel other people's translation jobs?"
Wait for my answers. Write each answer as a gate in the policy file in step 3.

## Step 3: the access policy file

Open `src/access.policy.ts`, or create it if the project has none, following the guard README
(`defineAccessPolicy`, `gate`, `filter`, `nobody`, `anyone`, checked with `satisfies AccessPolicy<Config>`).
If you create it, every collection and global of the config needs an entry: move each existing
`access` of the project into the file, and ask me for every rule you cannot read from the code.
Add these entries for this plugin:

collections: {
  "translator-provenance": { create: nobody, read: nobody, update: nobody, delete: nobody },
  "payload-jobs": "payload-default",
},
jobs: { run: <an admin gate, or a cron-secret gate>, queue: <an admin gate>, cancel: <an admin gate> },
plugins: {
  translator: {
    translate: <the gate from my first answer>,
    translateInBulk: <the gate from my second answer>,
    publish: <the gate from my third answer>,
    manageJobs: <the gate from my fourth answer>,
  },
},

Keep the `translator-provenance` entry only if you turn `provenance` on in step 4.

## Step 4: register the plugin and wrap the config

// payload.config.ts
import OpenAI from 'openai'
import { buildConfig } from 'payload'
import { withAccessPolicy } from '@focus-reactive/payload-plugin-guard'
import {
  createPayloadJobsRunner,
  createTranslationProvider,
  openAIComplete,
  translatorPlugin,
} from '@focus-reactive/payload-plugin-translator'
import { accessPolicy } from './access.policy'

export default withAccessPolicy(
  accessPolicy,
  buildConfig({
    // ...the existing config
    plugins: [
      translatorPlugin({
        collections: [Posts],
        access: accessPolicy.plugins.translator,
        translationProvider: createTranslationProvider({
          complete: openAIComplete({
            client: new OpenAI({ apiKey: process.env.OPENAI_API_KEY }),
            model: 'gpt-5.4-mini',
          }),
        }),
        runner: createPayloadJobsRunner(),
        provenance: true,
      }),
    ],
  })
)

Pass the same collection objects that `buildConfig` receives, not sanitized ones.
Run `payload generate:importmap` and `payload generate:types`, create a migration if the database is
SQL (`payload migrate:create`), then start the app.
A missing or wrong policy entry stops the boot with a list of what to fix.
Fix each item; never loosen a rule to make an error go away.

## Step 5: verify, and show me the output

With the app running, send each request and show me the status code.
Every one of them must be refused. If one succeeds, the policy is wrong: stop and tell me.

1. Anonymous enqueue, expect 401:
   curl -i -X POST http://localhost:3000/api/translator/enqueue -H 'Content-Type: application/json' -d '{"source_lng":"en","target_lng":"de","collection_slug":"posts","collection_id":["<post id>"]}'
2. The same request with the session cookie of a user whose role may not translate, expect 403.
3. The same request by a translator for a post that user may not update, expect 403.
4. Anonymous write to the provenance collection, expect 403:
   curl -i -X POST http://localhost:3000/api/translator-provenance -H 'Content-Type: application/json' -d '{}'
5. Anonymous queue run, expect 401:
   curl -i http://localhost:3000/api/payload-jobs/run?queue=translations

Then, as a user who may translate, open a post, translate it from `en` to `de`, and check the German locale.

Install

npm install @focus-reactive/payload-plugin-translator @focus-reactive/payload-plugin-guard openai

openai is optional — it backs the recipe below, and any OpenAI-compatible endpoint works in its place.

RequirementVersion
payload^3.90.0
@payloadcms/ui^3.90.0
@payloadcms/richtext-lexical^3.90.0
react^19 — the plugin accepts ^18 too, but current @payloadcms/ui and @payloadcms/richtext-lexical builds require 19
openai^4.50.0 (optional)

Your Payload config must have localization enabled, and the fields you want translated must be marked localized: true.

[!NOTE] Coming from 0.19 or earlier? Migrating from 0.19 lists what to change. Versioning has the terms and the list of what is already going.

Quickstart

Hand the plugin the same collection objects you pass to buildConfig, not the sanitized ones from payload.collections. The originals still carry localized: true on nested fields.

This is a whole config so that it runs as shown; in your project keep your own database adapter, and set PAYLOAD_SECRET in the environment before starting. The access policy grants each capability to a role of the users collection; the guard README covers the policy file in full.

// access.policy.ts
import { defineAccessPolicy, gate, nobody, panelUser } from '@focus-reactive/payload-plugin-guard'

const hasRole = (...roles: string[]) =>
  gate(({ req }) => roles.includes((req.user as { role?: string } | null)?.role ?? ''))
const isAdmin = hasRole('admin')
const isEditor = hasRole('admin', 'editor')

export const accessPolicy = defineAccessPolicy({
  collections: {
    users: { create: isAdmin, read: panelUser, update: isAdmin, delete: isAdmin, admin: isEditor },
    posts: { create: isEditor, read: isEditor, update: isEditor, delete: isAdmin },
    'payload-jobs': 'payload-default',
    'payload-kv': 'payload-default',
    'payload-locked-documents': 'payload-default',
    'payload-preferences': 'payload-default',
    'payload-migrations': { create: nobody, read: isAdmin, update: nobody, delete: nobody },
  },
  globals: {},
  jobs: { run: isAdmin, queue: isAdmin, cancel: isAdmin },
  plugins: {
    translator: { translate: isEditor, translateInBulk: isEditor, publish: isAdmin, manageJobs: isAdmin },
  },
})
// payload.config.ts
import { withAccessPolicy } from '@focus-reactive/payload-plugin-guard'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import OpenAI from 'openai'
import { buildConfig } from 'payload'
import type { CollectionConfig } from 'payload'
import {
  createPayloadJobsRunner,
  createTranslationProvider,
  openAIComplete,
  translatorPlugin,
} from '@focus-reactive/payload-plugin-translator'
import { accessPolicy } from './access.policy'

const Users: CollectionConfig = {
  slug: 'users',
  auth: true,
  fields: [{ name: 'role', type: 'select', options: ['admin', 'editor'] }],
}

const Posts: CollectionConfig = {
  slug: 'posts',
  fields: [
    { name: 'title', type: 'text', localized: true },
    { name: 'summary', type: 'textarea', localized: true },
  ],
}

export default withAccessPolicy(
  accessPolicy,
  buildConfig({
    admin: { user: 'users' },
    collections: [Users, Posts],
    db: sqliteAdapter({ client: { url: 'file:./payload.db' } }),
    localization: { defaultLocale: 'en', locales: ['en', 'de', 'fr'] },
    secret: process.env.PAYLOAD_SECRET ?? '',
    plugins: [
      translatorPlugin({
        collections: [Posts],
        access: accessPolicy.plugins.translator,
        translationProvider: createTranslationProvider({
          complete: openAIComplete({
            client: new OpenAI({ apiKey: process.env.OPENAI_API_KEY }),
            model: 'gpt-5.4-mini',
          }),
        }),
        runner: createPayloadJobsRunner(),
      }),
    ],
  })
)

Regenerate the admin import map so Payload picks up the plugin's components:

npx payload generate:importmap

Sign in as an editor and open a posts document. A Translate control now sits beside the document controls: choose en as the source and de as the target, and the German locale is filled in within a minute.

[!TIP] Rerun payload generate:importmap after adding or removing documentLevel() or collectionLevel(), or the admin renders without their controls. fieldLevel() adds no admin component, so it needs no regeneration.

What you can do

  • Translate one document — the control on the edit view queues a job for the target locale you pick, choosing a strategy and whether to publish the locale once it is filled in.
  • Translate a whole collection — a dashboard above the list view runs the selected documents, or all of them, and reports progress per locale.
  • Translate into several locales at once — targetSelection: 'multi' turns the target field on both the document and the collection surfaces into a multi-select, and every selected document is translated into every locale you picked. The default is one locale per run.
  • Translate a single field — a control on the field itself, answering in place without queueing anything. Needs both fieldLevel() in levels and withFieldTranslation on the field.
  • Auto-translate on save — wrap a collection in withAutoTranslate(collection, { targets }) and editing the source locale queues its own translations, with no one pressing anything. On a collection with drafts enabled it waits until the document is published; without drafts it fires on every save. Rapid edits are coalesced into one run.
  • Protect hand-written copy — the skip_existing strategy fills only empty target fields, and withFieldTranslation(field, { exclude: true }) keeps a field out of translation entirely.
  • Steer how it translates — systemPrompt replaces the instruction sent with every request, so tone, register, a glossary, or brand names that must stay untranslated are yours to set.
  • Bring any translation service — an OpenAI-compatible adapter ships in the box; anything else is a single function you write, which receives the text and returns the reply. You do not parse it or check it back — that is the plugin's job.
  • Run it in the background or inline — Payload Jobs by default, so an editor is not left waiting and a run can be cancelled or retried. createSyncRunner() translates inline instead, for tests and scripts.
  • Keep rich text intact — the structure of a rich-text field survives translation, and so do block types. Blocks and array items keep their ids too, except inside a localized container, where each locale owns its own rows and gets fresh ones.
  • Spot stale translations — with provenance on, the admin flags the locales whose source has changed since they were translated, and an editor can dismiss a flag without re-translating.

What travels: localized text, textarea and richText fields, at any depth inside groups, arrays, tabs and blocks. Every other field type reaches the target locale unchanged.

[!NOTE] Inside a rich-text paragraph, word order follows the source language and inline emphasis can land on the wrong word once the target language reorders the sentence. Container mode, available since 0.13.0 behind an opt-in flag, fixes both.

[!IMPORTANT] Mark each leaf field localized: true yourself. Payload lets a wrapper (group, array, blocks, tabs) carry localized and have nested fields inherit it, and a leaf without it of its own is left alone.

// Skipped — the nested title is not explicitly localized
{ name: 'meta', type: 'group', localized: true, fields: [{ name: 'title', type: 'text' }] }

// Translated
{ name: 'meta', type: 'group', localized: true, fields: [{ name: 'title', type: 'text', localized: true }] }

Contents

Configuration

translatorPlugin(config: TranslatorPluginConfig)
OptionTypeDefaultDescription
collectionsCollectionConfig[]—Required. Original collection configs to make translatable.
translationProviderTranslationProvider—Required. What actually translates the text.
runnerTaskRunnerProvider—Required. What runs the translation — in the background, or inline.
levelsTranslationLevel[][documentLevel(), collectionLevel()]Which translation surfaces to enable.
accessRecord<'translate' | 'translateInBulk' | 'publish' | 'manageJobs', Gate>-Required, no default. One gate from your access policy per capability, usually accessPolicy.plugins.translator. See Access control. Since v0.20.0.
maxDocumentsPerRequestnumber500The most documents one enqueue request may queue, picked one by one or with "select all". A larger request is refused with 400. Since v0.20.0.
targetSelection'single' | 'multi''single''multi' lets an editor pick several target locales for one run. Since v0.10.0.
provenanceboolean | { slug?: string }falseAdds a collection recording what each locale was translated from, so the admin can flag stale ones. Default slug translator-provenance.
lifecycleTranslationLifecycleCallbacks{}Server-side onQueued / onCompleted / onFailed callbacks.

Translation levels

Since v0.5.0; fieldLevel() since v0.6.0.

Levels are the surfaces the plugin adds. List the ones you want; each should appear at most once.

LevelWhat it adds
documentLevel()A Translate popup on the document edit view.
collectionLevel()A bulk translation dashboard above the list table.
fieldLevel()Turns on the per-field control. Not in the default set.
import { documentLevel, collectionLevel, fieldLevel } from '@focus-reactive/payload-plugin-translator'

translatorPlugin({
  collections: [Posts],
  translationProvider,
  runner,
  levels: [documentLevel(), collectionLevel(), fieldLevel()],
})

fieldLevel() on its own shows nothing: the control appears only on the fields you wrap with withFieldTranslation.

Per-field control and exclusion

import { withFieldTranslation } from '@focus-reactive/payload-plugin-translator'

export const Posts: CollectionConfig = {
  slug: 'posts',
  fields: [
    // A Translate control appears above this input (text, textarea, richText)
    withFieldTranslation({ name: 'title', type: 'text', localized: true }),

    // Never sent to the translation provider (any field type)
    withFieldTranslation({ name: 'sku', type: 'text', localized: true }, { exclude: true }),
  ],
}

The control translates from a source locale you pick, reading the saved document's value in that locale and writing the result into the locale you are editing. Unsaved edits in the form are invisible to it.

The control is an icon button above the input. It opens a small popup showing the direction — a source-locale select, an arrow, then the locale you are editing as the fixed target (en → fr). You choose the source; the target is always where you stand. Note this is the opposite direction from the document and collection controls, which translate out of the locale you are in.

The control needs a saved document, so it stays hidden while you are creating one. The result lands in the form unsaved — no save, no queue — and an Undo restores the previous value.

withFieldTranslation accepts text, textarea and richText; any other type is a compile error, so pass { exclude: true } for those. Fields inside blocks are supported.

[!WARNING] A localized blocks or array container has no per-field translation. Wrap the leaves, not the container. When the container itself is localized, each locale holds its own order and content, so there is no single field to translate across them: the control answers with a notice telling you to translate the whole document instead, which handles this case.

{ exclude: true } means never send this field to the provider — not leave it untouched. An excluded field keeps its target value when it has one, is filled from the source locale when the target is empty (so a required field does not fail validation on save), and is never sent for translation. Exclusion wins over the overwrite strategy.

Auto-translate on source change

Since v0.9.0.

Wrap a collection and edits to the source locale queue their own translations. On a collection with versions.drafts enabled this waits until the document is published; without drafts every save triggers it. Off unless you opt in, and a save that touched no translatable content queues nothing.

import { withAutoTranslate } from '@focus-reactive/payload-plugin-translator'

translatorPlugin({
  collections: [withAutoTranslate(Articles, { targets: ['de', 'fr'], debounceMs: 2000 })],
  translationProvider,
  runner,
})
KeyTypeDefaultDescription
targetsstring[]—Required. Locales to translate into. The source locale is always excluded.
strategy'overwrite' | 'skip_existing''overwrite'Replace every target field, or only fill empty ones.
debounceMsnumber0Delay before the queued job runs, coalescing rapid edits.
sourceLocalestringlocalization.defaultLocaleSource locale override for this collection.

[!IMPORTANT] Auto-translate only schedules the work. Nothing is translated unless your runner actually runs it — see Task runners.

Auto-translate acts as the admin-panel user who saved the source, and with that user's rights. Since v0.20.0. A save by a user without the translate capability, by a user of another auth collection, or with no user at all (a script, a seed, a Local API call without user) queues nothing. The job records who saved, and when it runs it checks that user's current capabilities and document rights again; if the user is gone or has lost them, nothing is written.

[!WARNING] Auto-translate publishes what it writes when the saver holds publish. A translation it queues off a published save by such a user is published in turn, not left as a draft. A save by a user without publish queues translations that stay drafts.

Drafts and publishing

Applies to every trigger: the admin controls, POST /api/translator/enqueue, and auto-translate. Publishing on translation needs the publish capability and the requester's right to publish the document.

Everything below describes a collection with versions.drafts enabled. Without drafts there is nothing to stage: a translation is written straight to the live document, and asking to publish on translation does nothing, silently.

Without publish-on-translation the translation is written as a draft version. The document's published state is untouched: a live page stays live, an unpublished one stays unpublished, and the new locale does not reach the public site until someone publishes it.

With publish-on-translation the translation is written as a draft and the target locale is then published — which happens whether or not any field actually needed translating. Only the translated locale is published; other locales keep the state they were in. Translating a document that is not currently published does make it live, carrying just that locale's content.

The source is the source locale's own current content — the newer draft when one exists, otherwise the published version, never a value Payload substitutes from another locale. Translating from a locale you have not filled in therefore translates nothing.

Two consequences worth knowing before relying on it:

  • Publishing publishes the current draft, whatever is in it. That includes pending edits nobody made for the translation's sake, and non-localized fields, which Payload stores once per document and cannot scope to a locale. Worth remembering before running translate-and-publish over a long list: every unpublished draft among them goes live.
  • skip_existing counts anything non-empty as translated. A translation waiting unpublished in a draft counts, so a reviewer's corrected text is published as it stands rather than re-translated. It has no notion of reviewed, and a locale the admin flags as out of date is still skipped (#118).

Translation providers

Since v0.11.0.

A provider is one method: take { 0: "Hello", 1: "World" } plus a source and target language, and return the same keys translated. Build one from a single request function with createTranslationProvider:

import { createTranslationProvider } from '@focus-reactive/payload-plugin-translator'

const provider = createTranslationProvider({
  complete: async ({ systemPrompt, userContent, responseSchema }) => {
    const reply = await myService.chat({ systemPrompt, userContent, schema: responseSchema })
    return reply.text // return the reply as it came; the plugin reads it
  },
})

Or implement the TranslationProvider interface directly if you need full control.

Steering the prompt

systemPrompt replaces the instruction sent with every translation request — the place for tone, register, a glossary, or brand terms that must survive untranslated. It receives the source and target language codes plus the prompt the plugin would have sent, so you can extend rather than replace:

createTranslationProvider({
  complete: openAIComplete({ client, model: 'gpt-5.4-mini' }),
  systemPrompt: ({ sourceLang, targetLang, defaultPrompt }) =>
    `${defaultPrompt}\nUse formal register. Leave product names in ${sourceLang} unchanged.`,
})

sourceLang is empty when the provider is expected to detect the language itself.

OpenAI and OpenAI-compatible gateways

openAIComplete works with any client exposing a Chat Completions chat.completions.create — the OpenAI SDK, Azure OpenAI, OpenRouter, a corporate proxy. You construct the client, so the SDK version is yours to choose.

createTranslationProvider({
  complete: openAIComplete({
    client: new OpenAI({
      apiKey: process.env.OPENROUTER_API_KEY,
      baseURL: 'https://openrouter.ai/api/v1',
    }),
    model: 'anthropic/claude-sonnet-4.5',
    sampling: { temperature: 0 },
    structuredOutput: 'json_object',
  }),
})

structuredOutput picks how the reply is asked for:

  • 'json_schema' (default) — the reply must satisfy a schema, so a compliant model cannot drop a field. Older models and some gateways reject it with a 400, and the schema has a per-model property ceiling that a very large document can exceed.
  • 'json_object' — asks only for valid JSON. No ceiling, but a field the model drops surfaces as a failed translation afterwards instead of being prevented.

sampling is sent only if you set it — several models reject the parameters outright. Pass { temperature: 0 } when you want translations to come out the same way twice.

[!NOTE] createOpenAIProvider({ apiKey }) still exists and builds the client for you. It is deprecated in favour of the two lines above — see Deprecated aliases.

Provider errors

Provider failures arrive as typed errors, each with a code and the original failure on cause.

Errorcode
NoContentErrorno-content
UnparseableReplyErrorunparseable-reply
KeySetMismatchErrorkey-set-mismatch
TransportErrortransport
ProviderConfigurationErrorconfig

All extend TranslationProviderError; the union of codes is exported as TranslationFailureCode.

Testing without a network

There is no built-in fake — supply your own complete, which reaches nothing and needs no API key:

const fake = createTranslationProvider({
  complete: async ({ userContent }) => {
    const input: Record<string, string> = JSON.parse(userContent)
    return JSON.stringify(
      Object.fromEntries(Object.entries(input).map(([k, v]) => [k, `[de] ${v}`]))
    )
  },
})

Task runners

RunnerBehaviour
createPayloadJobsRunner(options?)Translates in the background, one Payload Job per document. The normal choice.
createSyncRunner(options?)Translates immediately, before the call returns. No queue to run — handy in tests and scripts.

PayloadJobsRunnerOptions:

OptionTypeDefault
taskNamestring'translate_document'
queueNamestring'translations'
jobsCollectionCollectionSlug'payload-jobs'
autoRunfalse | { cron?: string; limit?: number }{ cron: '* * * * *', limit: 50 }
staleJobTimeoutMsnumber300000
retries{ attempts?: number; backoff?: { delay?: number; type: 'exponential' | 'fixed' } }{ attempts: 3, backoff: { type: 'exponential', delay: 5000 } }

[!WARNING] staleJobTimeoutMs must exceed the longest a single document translation can legitimately take. Set it too low and a translation still running is started again — the document is translated twice, and billed twice.

[!IMPORTANT] Cron autorun does not fire on serverless hosts such as Vercel, so jobs queue and wait. Pass createPayloadJobsRunner({ autoRun: false }) and drive the queue from your own cron through Payload's GET /api/payload-jobs/run?queue=translations, which your policy's jobs.run gate guards (see Jobs and the queue). POST /api/translator/run runs one job now for a signed-in user.

createSyncRunner keeps the status of what it ran in memory — the last 100 tasks, for an hour, adjustable with maxSize and ttlMs. A restart forgets them. Nothing is lost but the reporting: the translations themselves are already written.

Seeing finished jobs

Payload deletes a job the moment it completes, so the "Completed" state never appears in the status panels. Set jobs: { deleteJobOnComplete: false } in your Payload config to keep them — it is Payload's option, not the plugin's, and pruning what accumulates is yours to manage the same way.

Access control

Since v0.20.0.

The plugin declares four capabilities. Your access policy grants each one with a gate, and access: accessPolicy.plugins.translator hands them to the plugin. There is no default: a missing or partial access stops the boot.

// access.policy.ts
plugins: {
  translator: {
    translate: isEditor,
    translateInBulk: isEditor,
    publish: isAdmin,
    manageJobs: isAdmin,
  },
},
CapabilityLets a userAlso needs
translatetranslate one document or one field, read translation status and staleness, run or cancel their own jobsread on the source locale and update on the target locale of each document
translateInBulkqueue more than one document in one request, including "select all", and cancel their own jobs across a collectionthe same rights, on every document
publishpublish the target locale after translating itthe right to publish the document
manageJobsrun or cancel jobs other users queuedupdate on the job's document, or nothing to cancel a job whose document was deleted

The capability says who may act at all. The document rights come from the policy entries you already wrote for the collection: a user who cannot update a post cannot translate into it, whatever capabilities they hold. The admin shows the document's Translate control and the field-level translate button only to a user who holds translate and may update the document, and a refused request is shown as a message instead of being dropped. The bulk dashboard above a list shows only to a user who holds translate and translateInBulk and may update documents in that collection. When the user may not update every selected document, the dashboard says how many it queued, or that it queued nothing. A job in a document's translation status offers Retry, Run now and Cancel only to a user the server would let run and cancel it. The bulk Cancel translations button shows only when the user may cancel at least one queued translation in the collection, because without manageJobs it cancels only the user's own; afterwards the admin says how many it cancelled.

  • Only an admin-panel user (a user of admin.user whose access.admin allows them) can call the plugin. Anonymous callers get 401; users of another auth collection and users without the capability get 403.
  • A translation reads the source and writes the target as the user who asked for it, with Payload's access control on, including field rules. A queued job stores that user and checks their current capabilities and rights again when it runs. A job whose user is gone, has lost a right, or that names no user, writes nothing.
  • A job that has given up (Payload marked it as errored) is not revived by POST /api/translator/run, so its provider budget is not spent again; queue a new translation instead.
  • A job whose document was deleted can still be cancelled by the user who queued it or by a holder of manageJobs, and is never run.
  • Every endpoint that names a collection refuses one that is not in collections with 400.
  • Status reads show only documents the caller may read.
  • Dismissing a staleness flag needs update rights on the target locale, which must be one of the project's locales.
  • Inputs are capped: maxDocumentsPerRequest documents per enqueue (default 500), 100 ids per cancel, 256 KB per field value sent to the provider, and the request body size the guard allows. Errors carry a generic message; details go to the server log.
  • GET /api/translator/capabilities answers an admin-panel user with { "translate": boolean, "translateInBulk": boolean, "publish": boolean, "manageJobs": boolean }, so custom admin UI can hide controls; the server still checks every request.

What the plugin owns

SlugKindWritten byRead by
translator-provenance (with provenance on)collectionthe plugin onlyyour policy's read; nobody is the usual answer, since the admin reads it through the plugin

The collection needs an entry in your policy, and its create, update and delete are refused over REST, GraphQL and the Local API with overrideAccess: false, for every user.

Jobs and the queue

With createPayloadJobsRunner(), translations are Payload jobs in the translations queue, so the policy's jobs entry and the payload-jobs collection apply.

  • Keep 'payload-jobs': 'payload-default' in the policy.
  • jobs.run guards Payload's own GET /api/payload-jobs/run. Grant it to admins, and on a serverless host to your cron, for example with a gate that compares a bearer token to CRON_SECRET using safeEqual from the guard. Whoever triggers the run, each translation job still acts as the user who queued it, with that user's current rights.
  • jobs.queue and jobs.cancel guard Payload's own queue and cancel operations; the plugin queues and cancels through its own endpoints, which check the capabilities above.

Lifecycle callbacks

Since v0.7.0.

Nothing to set up beyond the config — no collection, no migration. A callback that throws is logged and never fails the translation.

translatorPlugin({
  collections,
  translationProvider,
  runner,
  lifecycle: {
    onQueued: (task) => log.info(task, 'translation queued'),
    onCompleted: (task) => log.info(task, 'translation done'),
    onFailed: (task, error) => log.error({ task, error }, 'translation failed'),
    onCancelled: (task) => log.info(task, 'translation cancelled'),
  },
})

Each task carries { collection, id, sourceLng, targetLng, strategy, handle }. handle names the run translating that locale: the value the enqueue answer gave, and the one DELETE /api/translator/cancel takes back. Since v0.16.0.

Each callback fires at most once per target locale, never per attempt: onQueued when the runner takes the work, then one of onCompleted, onFailed or onCancelled. onFailed means the locale will not be translated — retries are the runner's own business and are not reported, so there is no need to disable them. Since v0.16.0; onFailed previously fired on every failed attempt.

Two notes on "at most once". A second request for a locale a live run already covers joins that run instead of starting another, so both requests see the same handle and one set of events. And a locale already being translated when its run is cancelled is announced onCancelled and may still finish as onCompleted.

Provenance and staleness

Since v0.7.0.

Set provenance: true and the plugin adds a collection that records, for each document and target locale, what the source looked like when that locale was translated. The admin uses it to flag locales whose source has changed since, and an editor can dismiss a flag without re-translating. The record type is exported as TranslationProvenanceRecord if you want to read it yourself.

[!IMPORTANT] On a SQL database this adds a table. Generate and run a migration (payload migrate:create, then payload migrate; dev push works in development). MongoDB infers it with no migration. Leaving provenance off means no collection, no migration and no behaviour change.

[!NOTE] Upgrading from below 0.11.1. A locale can read as out of date once after the upgrade with nothing actually needing re-translation. Dismissing the flag or re-translating settles it.

HTTP endpoints you can call

Every endpoint lives under /api/translator/ and answers only an admin-panel user who holds the capability named below. Since v0.20.0. Requests with a body must send Content-Type: application/json.

MethodPathCapabilityWhen you need it
POST/api/translator/enqueuetranslate; translateInBulk for more than one document; publish with publish_on_translationStart translations from your own code: a migration, an import, any script running as a user.
POST/api/translator/runtranslate, and the job is yours or you hold manageJobsRun a queued job now.
POST/api/translator/fieldtranslateTranslate one field and get the result back. Mounted only when levels includes fieldLevel().
GET/api/translator/capabilitiesnoneWhat the signed-in user may do.

POST /enqueue takes source_lng, target_lng (one locale or a list), collection_slug and collection_id[], plus optional select_all, strategy ('overwrite' | 'skip_existing', default 'overwrite') and publish_on_translation (default false). Field names are snake_case. If the caller may not translate one of the collection_id documents, the answer is 403 and nothing is queued. It answers { "data": { "success": true, "queued": <translations>, "documents": <documents> } }. With select_all it queues only the documents the caller may update, so documents can be lower than the number of documents in the collection.

A script calls these endpoints as a user of admin.user: it signs in with POST /api/<admin user slug>/login and sends Authorization: JWT <token>. An API key is refused, because the endpoints accept only the session channel.

POST /run takes { "id": "<job id>" }.

POST /field takes collection_slug, doc_id, field_path, source_lng and target_lng. The field must be localized and the two locales must differ.

[!NOTE] The plugin mounts further routes under /api/translator/ to serve its own admin panels: status, cancel and staleness. They are not part of the published contract and may change in any release; drive the plugin through the endpoints above.

Exports reference

ExportKindPurpose
translatorPluginfunctionThe plugin itself.
documentLevel, collectionLevel, fieldLevelfunctionsTranslation surfaces for levels.
withFieldTranslationfunctionAttach a per-field control, or exclude a field.
withAutoTranslatefunctionOpt a collection into auto-translation.
createTranslationProviderfunctionBuild a provider from one complete function.
openAICompletefunctionChat Completions complete for a client you construct.
createPayloadJobsRunner, createSyncRunnerfunctionsThe two ways to run a translation.
toTaskFilterfunctionBuilds the document filter a runner accepts.
TranslationProviderError and subclassesclassesTyped provider failures.
TranslatorPluginConfigtypePlugin configuration.
TranslationProvider, TranslationInput, TranslationOutputtypesThe provider contract.
CompletionFn, CompletionRequest, TranslationProviderConfigtypesThe complete contract.
SystemPromptBuilder, SystemPromptContext, JsonSchemaObjecttypesPrompt and schema customization.
OpenAIClientShape, OpenAISamplingParams, OpenAIStructuredOutputtypesOpenAI adapter.
TaskRunnerProvider, PayloadJobsRunnerOptions, TaskFiltertypesTask runners.
TranslationLevel, TargetSelectionModetypesSurfaces and target selection.
AutoTranslateConfig, AutoTranslateStrategy, FieldTranslationConfigtypesCollection and field configuration.
TranslationTask, TranslationLifecycleCallbackstypesLifecycle callbacks.
TranslationProvenanceRecordtypeOne stored provenance record.

Experimental: rich text one container at a time

[!WARNING] Shipped in 0.13.0 behind experimental: { inlineMarks: true }, off by default, and deprecated on arrival — the next major removes the flag and makes container mode the only mode. Treat it as a schedule, not a permanent switch: do not build on the option itself.

With the flag off, a translated sentence keeps the source language's word order, and bold or a link can end up on the wrong word. a **red** car into French comes back as un rouge voiture — ungrammatical, with the emphasis misplaced.

With the flag on, the whole container — a paragraph, a heading, one list item — goes as a single string with its formatting written as numbered marks:

<1>a </1><2>red</2><3> car</3>

Your provider must return those markers intact — translated and reordered as the target language needs, but neither translated themselves nor dropped. The same sentence then comes back as une voiture rouge: the emphasis stays on the word it belonged to, and links travel with theirs.

The flag does nothing unless your provider declares that it can handle the markers:

createTranslationProvider({
  complete: openAIComplete({ client, model: 'gpt-5.4-mini' }),
  capabilities: { inlineMarks: true },
})

Declare it only for a service you trust to return the markers untouched — a plain machine-translation API would translate or drop them. A container whose reply comes back with broken markers is left in its source language rather than written back half-translated.

Switching the flag back off changes only future translations; documents already translated under it keep the structure they have.

Migrating from 0.19

0.20.0 moves the plugin onto @focus-reactive/payload-plugin-guard.

[!IMPORTANT] In versions up to and including 0.13.4, leaving out access left the translation endpoints open to anyone, signed in or not. If you ran one of those versions without access, review the translations, the payload-jobs rows and your translation provider's usage from that period, and upgrade. From 0.19.1, a request without a session gets 401 whatever the guard. From 0.20.0, access has no default and every endpoint refuses anonymous callers.

  1. Upgrade Payload to 3.90 or later and install @focus-reactive/payload-plugin-guard.
  2. Create src/access.policy.ts if the project has none, or extend it, with the translator entry from Access control, a translator-provenance entry when provenance is on, 'payload-jobs': 'payload-default' and a jobs entry, and wrap the config with withAccessPolicy.
  3. Replace access: { check } or new AnyAccessGuard() with access: accessPolicy.plugins.translator. AccessGuard, AccessGuardRequest and AnyAccessGuard are gone.
  4. basePath is gone: the endpoints live at /api/translator/... instead of /api/translate/.... POST /run/:id became POST /api/translator/run with { "id": "<job id>" }. DELETE /cancel-by-collection/:collection_slug became DELETE /api/translator/cancel-by-collection with { "collection_slug": "<slug>" }. Requests with a body must send Content-Type: application/json.
  5. Every translation reads and writes with the requesting user's rights, so a user who could translate before may now get 403 for a document they cannot update. Bulk requests need translateInBulk, publishing needs publish, and acting on someone else's job needs manageJobs.
  6. Auto-translate queues nothing for a save without an admin-panel user holding translate. Seeds and scripts that relied on it must call POST /api/translator/enqueue as a user, or save with user set.
  7. Jobs queued by 0.19 or earlier that name no requester write nothing when they run; queue them again.
  8. One enqueue request queues at most maxDocumentsPerRequest documents (default 500), a field value sent to the provider is capped at 256 KB, and a job that has given up is not revived by POST /run.
  9. A custom TaskRunnerProvider must implement findByIds(taskIds) on its task runner, which the run and cancel endpoints use to check each job before acting.
  10. The provenance collection is owned by the plugin: its create, update and delete are refused for every user, and who may read it is up to your policy.

Versioning

0.20.0 moved the plugin onto the guard; Migrating from 0.19 lists what changed. The surface still moves, and a later major will take a fair amount away. What it will not do is move silently. The terms are:

  • Nothing is removed without a deprecation first. The old name keeps working until the next major, and docs/DEPRECATIONS.md records why each one is going.
  • Releases follow semver, so a breaking change never arrives as a patch.
  • Anything added since 0.5.0 says which release it arrived in — as a Since note beside the feature here, and as an @since tag in its JSDoc, so your editor answers the question too. Older API predates the convention and carries no marker.

Already scheduled for a later major: everything in Deprecated aliases, and the experimental.inlineMarks flag, when container mode becomes the only mode. 0.20.0 removed none of them.

Deprecated aliases

Still exported, removed in a later major. The reasoning behind each is in docs/DEPRECATIONS.md.

DeprecatedUse instead
createTranslatePlugin, TranslateCollectionPlugintranslatorPlugin
TranslateCollectionPluginConfigTranslatorPluginConfig
translateKitFieldwithFieldTranslation
TranslateKitFieldConfigFieldTranslationConfig
OpenAITranslationProvider, createOpenAIProvidercreateTranslationProvider + openAIComplete
dryRun on a provider configYour own complete function

Troubleshooting

The Translate control does not appear. Run payload generate:importmap after registering the plugin, and restart the dev server.

Nested localized fields are skipped. You passed sanitized configs. collections must receive the same objects you give buildConfig — Payload's sanitizer strips localized from fields nested under a localized ancestor.

Jobs stay queued forever. Nothing is draining the queue. Check that autorun is enabled, or call Payload's GET /api/payload-jobs/run?queue=translations from a cron your policy's jobs.run admits, on platforms where autorun does not fire.

A job runs but writes nothing. A job writes only what the user who queued it may still write. Check that the user still exists, still holds translate (and publish if the job publishes), and may update the target locale; the server log names the reason.

Auto-translate queues nothing after a save. Only a save by an admin-panel user holding translate queues translations. A Local API write without user queues none.

The boot stops with "the access policy does not match the config". Add the entries it lists to your policy: the translator plugin entry, translator-provenance when provenance is on, and payload-jobs.

ProviderConfigurationError saying the model does not support the json_schema response format, or that the schema was rejected. The model or gateway would not accept the schema request, or the document was too large for it. Switch to structuredOutput: 'json_object'.

A per-field control on a field that is not text. withFieldTranslation adds a control only to text, textarea and richText; any other field type must be passed { exclude: true }.

License

MIT © Focus Reactive

Similar plugins