Fork notice — v1.4.0 (repo:
IT-PYX/payload-auto-translate-fork, package name unchanged:@itpyx/payload-auto-translate). Forked fromIT-PYX/payload-auto-translate@acfd6bd(npm 1.3.3) to fix the bugs that caused recurring untranslated content and 404s across the IT-PYX / AWD Payload sites. See "What changed in 1.4.0" below. Not published to npm yet — install from the git repo ("@itpyx/payload-auto-translate": "github:IT-PYX/payload-auto-translate-fork#v1.4.0").dist/is committed in this repo (unlike upstream) so a git install works with no build step — rebuild + commitdist/with every source change.
High-performance automated multi-language translation plugin for Payload CMS 3.x
Real-time background sync, Lexical Rich Text AST preservation, SEO slugification, and high-speed PostgreSQL bulk database crawler powered by LibreTranslate.
Payload CMS provides an excellent schema localization engine (localized: true), but it does not translate content out of the box—editors typically have to duplicate and translate content by hand.
@itpyx/payload-auto-translate automates the entire localization lifecycle:
- Real-Time Active Sync: Whenever an editor creates or edits content in the source locale (e.g., English), background workers automatically translate all target locales with debouncing.
- SEO-Grade Slug Localization: Automatically generates clean URL slugs (
inverter-split-ac->climatiseur-split-inverterin French,aire-acondicionado-split-inverterin Spanish) with German umlaut expansion and non-Latin character safety. - Smart Array & Block Merging: Intelligently preserves existing human-edited blocks, updates modified copy, and appends newly added blocks without mashing mismatched
blockTypes. - Lexical Rich Text AST Preservation: Traverses Lexical JSON text leaves while keeping headings, links, tables, and custom blocks structurally intact.
- Direct PostgreSQL Bulk Crawler: Includes a standalone CLI tool that crawls PostgreSQL tables directly, backfilling millions of words across existing websites in minutes with zero API overhead.
📖 Full Guide: For a complete walkthrough of configuring environment variables, Next.js transpilation, CLI backfill, and production Docker setups, see the Comprehensive Integration Guide.
Fixes the three recurring bugs found by the 2026-11-20 cross-site audit (EASCO, iClima, Lainexus, Gate Opener, Morthink + 3 EASCO sub-sites). All new options are additive with safe defaults — a site swaps the dependency only, no config change needed.
- No more cached echoes (fail-explicit). The module-level
translationCacheis deleted.translateBatchViaLibrenow returns only strings that actually translated; echoes, HTTP errors, timeouts and length mismatches are reported infailed(newtranslateBatchViaLibreDetailedreturns{ map, failed }) and never stored as translations.translateSingleTextthrows on final failure instead of returning the source text. - Fail loudly, retry properly. When a job leaves any string untranslated it throws (new option
failLoudly, defaulttrue) instead of saving English into the target locale; the persistent queue retries with backoff and marks the jobfailedaftermax_attempts. The worker also probes engine health (/languages) before picking up work and pauses — without consuming attempts — while the engine is down. - Loop guard that works on Local API. The
isAutoTranslatingcontext guard was proven unreliable onpayload.create/updatevia the Local API, so the queue now also tracks in-flight writes in a module-level set (inFlightTranslations) and the afterChange hooks skip docs in that set. - Schema-aware filtering. Only fields that are
localized: trueand text-like in the collection/global schema are extracted and translated (new optionschemaAwareFiltering, defaulttrue). Select/radio values (e.g.linkType) and non-localized fields are never translated and never reach the update payload — this fixes both the save-back validation failures and shared-column pollution (e.g.seo.*overwritten per locale).stripUnlocalizedFieldsnow deletes every non-localized field from the update payload exceptidandslug(it previously only deleted array/blocks fields). - Layout blocks translate.
"layout"is removed from the system field exclusions (new optiontranslateLayoutBlocks, defaulttrue). Layout blocks merge field-by-field, so human edits inside target-locale blocks survive a re-translation; block ids are still suffixed per locale as before. Sites need block-id suffixing on per-locale saves (EASCO already hassanitizeLayoutBlockIdsHook). - Smart sentence-case retry. The naive
toSentenceCase(which destroyed acronyms) is replaced by a smart normalizer that preserves a KEEP list (EASCO,WhatsApp,Wiegand,SUS304,Qualcomm,Android,NFC,LED,QR,USB,TCP/IP,RS485,IP65,PoE,WiFi,SDK,API, … — extendable viafallbackRetry.preserveWords), digit-containing words, camelCase words and singleI; KEEP words match as substrings, soGODENinside a heading is preserved. Echoed/failed strings are retried with two variants (normalized, then normalized +.) — for any echo, not only Title-Case headlines. - Slug freeze + NFC + change callback. An existing non-empty target slug is never regenerated (new option
slug.freezeExisting, defaulttrue). Slugs are NFC-normalized before comparison and before writing. Every slug the plugin writes that differs from the previously stored one is reported viaslug.onSlugChange({ collection, docId, locale, oldSlug, newSlug })(default: a loud log) so a future auto-redirect step can consume it. The fork itself creates no redirects. Note: the merge previously overwrote the target slug with the source slug on every job — the freeze re-asserts the stored slug after the merge. - Echo merge fix.
mergePreservingExistingnow re-translates values that are echo-like relative to the source (case-/punctuation-insensitive equality, or missing target script for ar/ru/ja) — previously only byte-identical values were replaced, so sentence-cased echoes froze in target locales forever (this is what froze the v1.1.0 sub-sites' translations).
Out of scope for this fork: self-hosting LibreTranslate (the shared engine stays), slug-freeze auto-redirects, deploy guardrails / nightly crawls, and rolling the fork out to any site.
- Payload CMS:
^3.0.0 - Database: PostgreSQL (via
@payloadcms/db-postgres) - Node.js:
>=18.20.0or>=20.9.0 - LibreTranslate: Self-hosted or dedicated LibreTranslate instance
pnpm add @itpyx/payload-auto-translate pg dotenv
# or
npm install @itpyx/payload-auto-translate pg dotenv
# or
yarn add @itpyx/payload-auto-translate pg dotenvimport { buildConfig } from 'payload'
import { postgresAdapter } from '@payloadcms/db-postgres'
import { autoTranslatePlugin } from '@itpyx/payload-auto-translate'
export default buildConfig({
localization: {
locales: [
{ label: 'English', code: 'en' },
{ label: 'Español', code: 'es' },
{ label: 'Français', code: 'fr' },
{ label: 'Deutsch', code: 'de' },
{ label: 'العربية', code: 'ar' },
{ label: '日本語', code: 'ja' },
],
defaultLocale: 'en',
fallback: true,
},
db: postgresAdapter({
pool: { connectionString: process.env.DATABASE_URL },
}),
plugins: [
autoTranslatePlugin({
engine: {
url: process.env.LIBRETRANSLATE_URL || 'http://127.0.0.1:5000',
apiKey: process.env.LIBRETRANSLATE_API_KEY,
},
sourceLocale: 'en',
targetLocales: ['es', 'fr', 'de', 'ar', 'ja'],
activeTranslation: {
enabled: true,
concurrency: 2,
triggerOn: ['create', 'update'],
translateDrafts: true, // Preserves draft status in collections with versions
},
// Optional: Automatic SEO slug translation
slug: {
enabled: true, // Enable automatic translated slugs
latinLocalesOnly: true // Preserves clean ASCII slugs for non-Latin (ar, ja)
},
// Optional: Configure specific collections
collections: {
pages: true,
blog: {
translateSlug: true,
excludedFields: ['authorNotes', 'internalReview'],
},
},
}),
],
})Add to your .env:
LIBRETRANSLATE_URL=http://your-vps-ip:5000
LIBRETRANSLATE_API_KEY=your_optional_api_keyIf your CMS runs within Next.js, add the package to transpilePackages in next.config.mjs:
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ['@itpyx/payload-auto-translate'],
}
export default nextConfig| Option | Type | Default | Description |
|---|---|---|---|
engine.url |
string |
process.env.LIBRETRANSLATE_URL || 'http://127.0.0.1:5000' |
Base URL of your LibreTranslate instance. |
engine.apiKey |
string |
process.env.LIBRETRANSLATE_API_KEY |
Optional API key if your LibreTranslate server requires authentication. |
sourceLocale |
string |
Payload defaultLocale || 'en' |
The master locale from which translations are generated. |
targetLocales |
string[] |
All other configured locales | Array of target language codes to translate into. |
activeTranslation.enabled |
boolean |
true |
Enables real-time background translation on editorial save. |
activeTranslation.concurrency |
number |
2 |
Number of concurrent documents processed in the queue. |
activeTranslation.triggerOn |
('create' | 'update')[] |
['create', 'update'] |
Operations that trigger background translation. |
activeTranslation.translateDrafts |
boolean |
true |
Translates drafts without prematurely publishing them. |
slug.enabled |
boolean |
false |
Enable automatic SEO slug generation for localized documents. |
slug.latinLocalesOnly |
boolean |
true |
If true, only translates slugs for Latin locales (es, fr, de, it, pt) and preserves ASCII slugs for non-Latin (ar, ru, ja). |
slug.sourceField |
string |
'title' |
Field to derive slug from (falls back to 'name'). |
slug.slugify |
function |
Built-in SEO slugifier | Custom function: (title, locale, currentSlug) => string. |
customFieldExclusions |
string[] |
[] |
Field names to exclude from translation globally. |
customValueExclusions |
string[] |
[] |
Specific text strings to skip during translation globally. |
customValuePatterns |
(string | RegExp)[] |
[] |
Custom regex patterns or strings to skip during translation (e.g. hardware specs like [/^IP\d+/, /^RS-?485/i]). |
fallbackRetry |
FallbackRetryOptions |
{ enabled: false } |
Optional fallback retry for strings returning untranslated (e.g., Title Cased headlines). |
collections |
Record<string, boolean | CollectionConfigOptions> |
Auto-detected | Selectively enable, exclude fields, or toggle slug translation per collection. |
globals |
Record<string, boolean | CollectionConfigOptions> |
Auto-detected | Selectively enable or exclude fields per global. |
disabled |
boolean |
false |
Master kill-switch to temporarily disable the plugin. |
When slug.enabled: true is set (or translateSlug: true on a specific collection):
- German Umlaut Expansion: Automatically maps
ä -> ae,ö -> oe,ü -> ue,ß -> ss(e.g.Lüftungstechnik Köln->lueftungstechnik-koeln). - Accents & Diacritics: Automatically strips accents across French, Spanish, Italian, and Portuguese (
Climatisation Écologique->climatisation-ecologique). - Non-Latin Protection: When
latinLocalesOnly: true(default), non-Latin languages (ar,ja,ru,zh) safely preserve the base ASCII slug, avoiding broken percent-encoded URLs (%D8%A7%D9%84%D...). When set tofalse, clean Unicode characters are preserved. - Human Edit Protection: Only generates a translated slug if the target slug is empty or identical to the default source English slug. Manually customized slugs are never overwritten.
For initial migrations, importing large catalogs, or translating existing records, use the standalone Database Crawler. It connects directly to PostgreSQL via raw SQL, inspects all tables with a _locale column, and populates missing target rows in high-speed parallel batches.
# 1. Dry run (inspect translatable tables and strings without writing to the database):
pnpm payload-auto-translate
# 2. Live migration (writes translated records directly to PostgreSQL):
pnpm payload-auto-translate --live
# 3. Limit translation to specific tables:
pnpm payload-auto-translate --live --tables=pages,products
# 4. Enable fallback retry for Title Case / Headline echoes:
pnpm payload-auto-translate --live --fallback-retry --fallback-strategy=sentence-case
# 5. Skip domain-specific tokens or hardware specs via patterns:
pnpm payload-auto-translate --live --value-patterns="/^IP\d+$/i,/^RS-?485$/i"
# 6. Custom .env file path:
pnpm payload-auto-translate --live --env=/path/to/.envAdd helper scripts to your CMS package.json:
{
"scripts": {
"translate:dry": "payload-auto-translate",
"translate:bulk": "payload-auto-translate --live"
}
}The plugin exposes secure, authenticated endpoints under your Payload API router:
GET /api/auto-translate/status: Returns LibreTranslate connectivity, supported language codes, active queue stats, and bulk crawler progress.POST /api/auto-translate/start-bulk: Asynchronously triggers a bulk migration across all localized tables.GET /api/auto-translate/bulk-progress: Polls live migration progress (tables processed, total strings, translated strings, inserted/updated counts).
To run your own free, unlimited translation instance on your server using Docker:
docker run -d \
--name libretranslate \
-p 5000:5000 \
--restart unless-stopped \
libretranslate/libretranslate:latest \
--load-only en,es,fr,de,ar,pt,ru,jaMIT License. Copyright (c) 2026 IT-PYX.