npm version MIT License Payload CMS v3 Next.js TypeScript

payload-plugin-dictionary

A high-performance Payload CMS v3 plugin that moves static front-end translation keys into your database. Empower content editors to manage UI microcopy directly in the Admin Panel, with instant on-demand cache revalidation and zero required third-party dependencies.

Get Started View on GitHub
$ pnpm add payload-plugin-dictionary
Traditional Static i18n (en.json) With payload-plugin-dictionary
Hardcoded in Git repository Managed in Payload Admin Panel
Copy changes require PRs & redeployments Instant updates with zero downtime
Content editors cannot modify microcopy Content editors have full localized control
Often requires bulky client bundles Server Components with automatic cache eviction

✨ Features

Everything you need to manage frontend translations at scale.

🗄️

Database-Backed Translations

Moves static translation keys into a dedicated translations collection with native localization support.

⚡

Next.js Data Cache Integration

Wrapped with unstable_cache and tagged with 'payload-translations' for millisecond response times.

🔄

Instant Revalidation

Automatically invalidates cache tags when translations are created, updated, or deleted via collection hooks.

⚛️

Zero-Dependency Mode

Full standalone support with t('key') functions for both Server and Client Components.

🔌

next-intl & i18next Compatible

Seamlessly acts as the dynamic message provider for your existing i18n library.

🌐

Built-in REST Endpoint

Direct HTTP access via GET /api/dictionary/:namespace with caching headers.

🛡️

Type-Safe CLI Generator

Run npx payload-dictionary generate to get full TypeScript autocompletion from your DB keys.

🔒

Data Integrity

Enforces dot-separated key notation and composite uniqueness across (namespace, key) pairs.


📦 Installation

Install with your favorite package manager.

bash
# Using pnpm
pnpm add payload-plugin-dictionary

# Using npm
npm install payload-plugin-dictionary

# Using yarn
yarn add payload-plugin-dictionary

Peer Dependencies

PackageVersionRequired
payload^3.90.0Yes
next^15.0.0 || ^16.0.0Yes
react^19.0.0Optional (client only)

⚙️ Configuration

Add dictionaryPlugin to your payload.config.ts

payload.config.ts
import { buildConfig } from 'payload'
import { dictionaryPlugin } from 'payload-plugin-dictionary'

export default buildConfig({
  localization: {
    locales: ['en', 'ar', 'fr'],
    defaultLocale: 'en',
    fallback: true,
  },
  plugins: [
    dictionaryPlugin({
      namespaces: ['common', 'auth', 'marketing'],
      defaultNamespace: 'common',
    }),
  ],
})

Plugin Options

OptionTypeRequiredDefaultDescription
namespaces string[] Yes — Array of permitted namespaces
defaultNamespace string No namespaces[0] Default namespace for new documents

🚀 Usage Guide

Choose standalone mode or integrate with your existing i18n library.

1. React Server Components

Call getTranslations() in any Server Component:

app/[locale]/page.tsx
import { getTranslations } from 'payload-plugin-dictionary/cache'

export default async function HomePage({ params }) {
  const { locale } = await params
  const t = await getTranslations('common', locale)

  return (
    <main>
      {/* Basic lookup */}
      <h1>{t('home.title')}</h1>

      {/* Variable interpolation */}
      <p>{t('welcome.user', { name: 'Sarah' })}</p>

      {/* Fallback if key is missing */}
      <button>{t('button.submit', 'Submit')}</button>
    </main>
  )
}

2. React Client Components

Wrap your layout with <DictionaryProvider>, then use useTranslations() anywhere:

app/[locale]/layout.tsx — Server Component
import { getDictionary } from 'payload-plugin-dictionary/cache'
import { DictionaryProvider } from 'payload-plugin-dictionary/client'

export default async function LocaleLayout({ children, params }) {
  const { locale } = await params
  const dictionary = await getDictionary('common', locale)

  return (
    <html lang={locale}>
      <body>
        <DictionaryProvider dictionary={dictionary}>
          {children}
        </DictionaryProvider>
      </body>
    </html>
  )
}
components/CounterButton.tsx — Client Component
'use client'

import { useTranslations } from 'payload-plugin-dictionary/client'
import { useState } from 'react'

export function CounterButton() {
  const t = useTranslations()
  const [count, setCount] = useState(0)

  return (
    <div>
      <button onClick={() => setCount(c => c + 1)}>
        {t('button.click_me')} ({count})
      </button>
      <p>{t('items.count', { count })}</p>
    </div>
  )
}

Using with next-intl

Supply the dictionary messages directly to next-intl:

i18n/request.ts
import { getRequestConfig } from 'next-intl/server'
import { getDictionary } from 'payload-plugin-dictionary/cache'

export default getRequestConfig(async ({ requestLocale }) => {
  const locale = (await requestLocale) || 'en'
  const messages = await getDictionary('common', locale)

  return { locale, messages }
})

Then consume with standard next-intl APIs:

components/Header.tsx
import { useTranslations } from 'next-intl'

export function Header() {
  const t = useTranslations()
  return <h1>{t('nav.home')}</h1>
}

Translator Function API

The t function returned by getTranslations() and useTranslations() provides:

SignatureDescriptionExample
t(key)Looks up key; returns key string if missingt('button.submit')
t(key, params)Replaces {var} placeholders with valuest('greeting', { name: 'Alex' })
t(key, fallback)Returns fallback text if key is missingt('btn.save', 'Save')
t(key, params, fallback)Replaces placeholders with fallback if missingt('hello', { name: 'Alex' }, 'Hi')
t.has(key)Returns true if key existst.has('banner.alert')
t.raw(key)Returns raw uninterpolated string or undefinedt.raw('welcome')
t.dictionaryDirect reference to Record<string, string>Object.keys(t.dictionary)

🌐 Built-in REST API

The plugin automatically registers an HTTP endpoint on your Payload server.

GET /api/dictionary/:namespace?locale=:locale

Returns a flat Record<string, string> of all translations for the given namespace and locale.

Request
GET /api/dictionary/common?locale=ar
Response
{
  "button.submit": "إرسال",
  "button.cancel": "إلغاء",
  "nav.home": "الرئيسية"
}

Response Headers: Cache-Control: public, s-maxage=3600, stale-while-revalidate=86400


🛠️ TypeScript CLI Generator

Generate strongly-typed definitions from your database keys for IDE autocompletion.

bash
npx payload-dictionary generate
Generated: dictionary.d.ts
/**
 * Auto-generated by payload-dictionary. Do not edit manually.
 */
export type CommonTranslationKeys =
  | 'button.submit'
  | 'button.cancel'
  | 'home.title'

export type AuthTranslationKeys =
  | 'login.button'
  | 'error.invalid_credentials'

export type AllTranslationKeys =
  | `common:${CommonTranslationKeys}`
  | `auth:${AuthTranslationKeys}`

🔄 Cache Architecture & Invalidation

Automatic cache invalidation ensures editors see instant updates.

sequenceDiagram
    autonumber
    actor Admin as Content Editor
    participant Payload as Payload Admin Panel
    participant DB as Database
    participant NextCache as Next.js Data Cache
    actor User as Frontend User

    Admin->>Payload: Updates "button.submit" to "Save"
    Payload->>DB: Saves localized document
    Payload->>NextCache: revalidateTag('payload-translations')
    User->>NextCache: Requests page
    NextCache->>DB: Cache miss → fetches updated dictionary
    NextCache-->>User: Returns updated translation ("Save")
    

📁 Package Entrypoints

payload-plugin-dictionary
Plugin initialization & root types — dictionaryPlugin(), createTranslator()
payload-plugin-dictionary/cache
Server-only — getTranslations(), getDictionary()
payload-plugin-dictionary/client
Client-side — <DictionaryProvider>, useTranslations(), useDictionary()