Mhmod-Hsn

payload plugin dictionary

by Mhmod-Hsn
Localized content
v3
^3.90.0

Overview

Summary generated from the README

Adds a localized translations collection to Payload so editors can manage UI microcopy such as buttons and labels from the admin panel. Provides cached server-side lookups with Next.js tag revalidation on change, a client provider with a translation hook, and a REST endpoint. Works standalone or as a message source for next-intl. Requires Payload 3.90 or newer and Next.js 15 or 16.

Features

  • Translations collection with native Payload localization and namespaces
  • Cached lookups via Next.js data cache, revalidated on create, update and delete
  • Translator function with interpolation, fallbacks, has and raw helpers
  • Client DictionaryProvider and useTranslations hook for client components
  • REST endpoint returning a namespace dictionary per locale with cache headers
  • CLI that generates TypeScript key types from database keys

Use cases

  • Let content editors change button and navigation labels without a redeploy
  • Feed database-managed messages into next-intl for a multi-language Next.js site
  • Get typed autocompletion for translation keys stored in the database

From the author

A Payload CMS v3 plugin that moves static frontend translation keys into the database, enabling content editors to manage UI translations with full localization support.

Installation

npm i payload-plugin-dictionary

3

Stars

0

Forks

0

Open Issues

1 months ago

Last Updated

15

Weekly Downloads

v1.0.1

npm Version

466.1 KB

Unpacked Size

0

Dependencies

GitHub stars

3+3 since Oct 11

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20263
Dec 4, 20263
Dec 3, 20263
Dec 2, 20263
Dec 1, 20263
Nov 30, 20263
Nov 29, 20263
Nov 28, 20263
Nov 27, 20263
Nov 26, 20263
Nov 25, 20263
Nov 24, 20263
Nov 23, 20263
Nov 22, 20263
Nov 21, 20263
Nov 20, 20263
Nov 19, 20263
Nov 18, 20263
Nov 17, 20263
Nov 16, 20263
Nov 15, 20263
Nov 14, 20263
Nov 13, 20263
Nov 12, 20263
Nov 11, 20263
Nov 10, 20263
Nov 9, 20263
Nov 8, 20263
Nov 7, 20263
Nov 6, 20263
Nov 5, 20263
Nov 4, 20263
Nov 3, 20263
Nov 2, 20263
Nov 1, 20263
Oct 31, 20263
Oct 30, 20263
Oct 29, 20263
Oct 28, 20263
Oct 27, 20263
Oct 26, 20263
Oct 25, 20263
Oct 24, 20263
Oct 23, 20263
Oct 22, 20263
Oct 21, 20263
Oct 20, 20263
Oct 19, 20263
Oct 18, 20263
Oct 17, 20263
Oct 16, 20263
Oct 15, 20262
Oct 14, 20262
Oct 13, 20262
Oct 12, 20260
Oct 11, 20260
npm weekly downloads

11−244 since Oct 15

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 202611
Dec 4, 202611
Dec 3, 202610
Dec 2, 202625
Dec 1, 202630
Nov 30, 202632
Nov 29, 202632
Nov 28, 202631
Nov 27, 202629
Nov 26, 202628
Nov 25, 202614
Nov 24, 202611
Nov 23, 202613
Nov 22, 202614
Nov 21, 202615
Nov 20, 202621
Nov 19, 202622
Nov 18, 202620
Nov 17, 202620
Nov 16, 202617
Nov 15, 202615
Nov 14, 202614
Nov 13, 202613
Nov 12, 202618
Nov 11, 202621
Nov 10, 202625
Nov 9, 202631
Nov 8, 202634
Nov 7, 202641
Nov 6, 202638
Nov 5, 202635
Nov 4, 202634
Nov 3, 202637
Nov 2, 202650
Nov 1, 202663
Oct 31, 2026216
Oct 30, 2026218
Oct 29, 2026214
Oct 28, 2026212
Oct 27, 2026208
Oct 26, 2026191
Oct 25, 2026182
Oct 24, 202635
Oct 23, 202630
Oct 22, 202658
Oct 21, 2026313
Oct 20, 2026308
Oct 19, 2026305
Oct 18, 2026297
Oct 17, 2026283
Oct 16, 2026283
Oct 15, 2026255

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

Health Score

56/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/1415671952-root.svg)](https://payloaddirectory.dev/plugins/1415671952-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1415671952-root"><img src="https://payloaddirectory.dev/badge/1415671952-root.svg" alt="Payload Directory"></a>
Updated Oct 22, 2026Created Oct 12, 2026Published Oct 22, 2026

README

payload-plugin-dictionary

npm version Documentation License: MIT Payload CMS Next.js TypeScript

A high-performance Payload CMS v3 plugin that migrates static front-end translation keys (en.json, ar.json, fr.json) into your database. Empower content editors to manage UI microcopy—such as buttons, navigation labels, headers, and error messages—directly within the Payload Admin panel, with instant on-demand cache revalidation and zero required third-party frontend dependencies.

🌐 Website & Documentation: https://mhmod-hsn.github.io/payload-plugin-dictionary/


🌟 Why This Plugin?

Traditional Static i18n (en.json)With payload-plugin-dictionary
Hardcoded in Git repositoryManaged in Payload Admin Panel
Copy changes require Pull Requests & redeploymentsInstant updates with zero downtime
Content editors cannot modify microcopyContent editors have full localized control
Often requires bulky client bundlesNext.js Server Components with automatic cache eviction

✨ Features

  • 🗄️ 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', ensuring database queries are cached and served in milliseconds.
  • 🔄 Instant On-Demand Revalidation: Automatically invalidates cache tags when translations are created, updated, or deleted via Payload collection hooks.
  • ⚛️ Zero Third-Party Dependency Mode: Full standalone support with callable t('key') functions for React Server Components and Client Components (<DictionaryProvider> + useTranslations()).
  • 🔌 Seamless next-intl & i18next Compatibility: Easily acts as the dynamic message provider for existing i18n libraries.
  • 🌐 Built-in REST Endpoint: Direct HTTP access via GET /api/dictionary/:namespace?locale=:locale with HTTP caching headers.
  • 🛡️ Type Safety & CLI Generator: Run npx payload-dictionary generate to generate TypeScript types directly from database keys for full IDE autocompletion.
  • 🔒 Data Integrity: Enforces dot-separated key notation (e.g., auth.login_button) and ensures composite uniqueness across (namespace, key) pairs.

📦 Installation

# Using pnpm
pnpm add payload-plugin-dictionary

# Using npm
npm install payload-plugin-dictionary

# Using yarn
yarn add payload-plugin-dictionary

Peer Dependencies

  • payload: ^3.90.0
  • next: ^15.0.0 || ^16.0.0
  • react: ^19.0.0 (optional; only needed if using client <DictionaryProvider> or useTranslations)

⚙️ Configuration

Add dictionaryPlugin to your 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',
    }),
  ],
  // ... your remaining Payload configuration
})

Plugin Options

OptionTypeRequiredDefaultDescription
namespacesstring[]Yes—Array of permitted namespaces (e.g. ['common', 'auth']).
defaultNamespacestringNonamespaces[0]Default namespace selected when creating new translation documents.

🚀 Usage Guide

You can use this plugin in two ways:

  1. Standalone (Zero Dependencies): Using our built-in getTranslations, <DictionaryProvider>, and useTranslations() hook.
  2. With an i18n Library (next-intl): Supplying the dictionary messages directly to next-intl.

Option 1: Standalone (Zero Dependencies)

1. React Server Components (RSC)

In any React Server Component, call getTranslations():

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

export default async function HomePage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params
  const t = await getTranslations('common', locale)

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

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

      {/* 3. Safe fallback if key is missing */}
      <button>{t('button.submit', 'Submit')}</button>
    </main>
  )
}
2. React Client Components

To use translations inside 'use client' components, fetch the dictionary in your Server Layout and wrap the children with <DictionaryProvider>:

// 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,
}: {
  children: React.ReactNode
  params: Promise<{ locale: string }>
}) {
  const { locale } = await params

  // Fetch raw dictionary for the client provider
  const dictionary = await getDictionary('common', locale)

  return (
    <html lang={locale}>
      <body>
        <DictionaryProvider dictionary={dictionary}>{children}</DictionaryProvider>
      </body>
    </html>
  )
}

Now call useTranslations() in any Client Component anywhere in the tree:

// components/CounterButton.tsx
'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>

      {/* Interpolation in client components */}
      <p>{t('items.count', { count })}</p>

      {/* Fallback support */}
      <button onClick={() => setCount(0)}>{t('button.reset', 'Reset Counter')}</button>
    </div>
  )
}
3. 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('button.save', 'Save Changes')
t(key, params, fallback)Replaces placeholders with fallback text if key is missingt('hello', { name: 'Alex' }, 'Hello Alex')
t.has(key)Returns true if key exists in dictionaryif (t.has('banner.alert')) ...
t.raw(key)Returns raw uninterpolated string or undefinedt.raw('welcome')
t.dictionaryDirect reference to Record<string, string> mapObject.keys(t.dictionary)

Option 2: Using with next-intl

If your project already uses next-intl, payload-plugin-dictionary integrates seamlessly as the message source.

Configure i18n/request.ts:

// 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'

  // Fetch from Payload database with automatic Next.js caching
  const messages = await getDictionary('common', locale)

  return {
    locale,
    messages,
  }
})

Consume in your components using standard next-intl APIs:

import { useTranslations } from 'next-intl'

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

🌐 Built-in REST API

The plugin automatically registers an HTTP REST endpoint on your Payload server:

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

Example Request

GET /api/dictionary/common?locale=ar

Example Response

{
  "button.submit": "إرسال",
  "button.cancel": "إلغاء",
  "nav.home": "الرئيسية",
  "footer.copyright": "جميع الحقوق محفوظة © 2026"
}

Response Headers

  • Content-Type: application/json
  • Cache-Control: public, s-maxage=3600, stale-while-revalidate=86400

🛠️ TypeScript CLI Type Generator

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

# Run the generator
npx payload-dictionary generate

Generated Output (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

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', 'max')
    User->>NextCache: Requests page
    NextCache->>DB: Cache miss -> fetches updated dictionary
    NextCache-->>User: Returns updated translation ("Save")
  • Invalidation occurs automatically on afterChange and afterDelete hooks.
  • Compatible with Next.js 15 and Next.js 16 cache models.
  • Gracefully handles execution outside Next.js request contexts (e.g., test suites, CLI tools).

📁 Package Entrypoints

SubpathTargetUse Case
payload-plugin-dictionarysrc/index.tsPlugin initialization & root types
payload-plugin-dictionary/cachesrc/cache/getDictionary.tsgetTranslations(), getDictionary() (Server-only)
payload-plugin-dictionary/clientsrc/client/index.tsx<DictionaryProvider>, useTranslations(), useDictionary() (Client)

🧪 Testing

The repository includes complete integration and end-to-end tests:

# Run unit & integration tests (Vitest)
pnpm test:int

# Run admin panel E2E tests (Playwright)
pnpm test:e2e

# Run linter
pnpm lint

# Build production bundle
pnpm build

📄 License

MIT © Mahmoud Hassan

Similar plugins