TOTP_TEXTS (en, pl) merged over payload-2fa's, project translations still win, twoFactor.texts: false keeps the package's; tab titles on the 2FA views (TOTP_VIEW_TITLE). CookieButton lifts above the footer (avoid, default COOKIE_BUTTON_AVOID; side; bottomOverlap; --ipal-cookie-button-inset). Admin language keeps following the browser (no fallbackLanguage change). Merge addition: the branch had no CHANGELOG entry — both items added under New in the one Unreleased section, plus Requires project changes item 6 (CookieButton).
22 KiB
i18n
Localization: locale config for Payload, language negotiation (cookie / Accept-Language / default), locale-aware path building, language switching without 404.
Config (payload.config.ts)
ipalKit({
i18n: {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
// { code: 'ar', label: 'العربية', rtl: true },
],
// fallback: true, // default true
},
})
| Field | Default | What it does |
|---|---|---|
defaultLocale |
— (required) | default language; must be in locales |
locales |
— (required, min. 1) | { code, label, rtl? }; code in the form pl, en, pt-BR |
fallback |
true |
Payload's localization.fallback (see below) |
The i18n option is required (type I18nConfig). The plugin sets config.localization
from it (overriding the project's own localization). Validation is eager — already when
ipalKit() is called, also with enabled: false: an empty list, missing code/label,
duplicate codes, a defaultLocale not in the list, a bad code format → error [ipal] i18n: ....
fallback: true and saving. Reading a language with no value returns the default language's value —
and saving the document persists it: saving a page (in the admin panel or with payload.update) in any
language writes the PL text into localized fields that were empty in EN/DE (e.g. an empty
block subheading gets the Polish one). Result: invisible missing translations turn into Polish
text on the EN/DE page. So:
- translate every field in every language (do not rely on fallback),
- migration/seed scripts read with
fallbackLocale: falseand write only what they set (context: { ipalSkipAutoFill: true }— seo.md); check data you change on a database copy first, fallback: falsealso turns off reading from the default language (empty fields on the EN/DE page) — a deliberate project decision.
Front end — helpers
All helpers are pure (they take the config as an argument). Keep your
i18nConfig in one place and import it where needed.
import {
getLocaleCodes, getDefaultLocale, isValidLocale, getLocaleDefinition,
negotiateLocale, buildLocalizedPath, switchLocalePath,
getLocalizedSlugs, LOCALE_COOKIE_NAME,
} from '@intecion/ipal-kit'
const config = { defaultLocale: 'pl', locales: [{code:'pl',label:'Polski'},{code:'en',label:'English'}] }
getLocaleCodes(config) // ['pl', 'en']
isValidLocale('de', config) // false
Building paths
// document fetched with locale:'all' → slug is a map { pl, en }
const doc = await payload.findByID({ collection: 'pages', id, locale: 'all' })
const slugs = getLocalizedSlugs({ slugField: doc.slug, config })
// { pl: 'o-nas', en: 'about' }
buildLocalizedPath({ slugs, locale: 'en', config }) // '/en/about'
// the home slug ('home') collapses to the root:
buildLocalizedPath({ slugs: { en: 'home' }, locale: 'en', config }) // '/en'
Type trap (TypeScript): with
locale: 'all'Payload returns, at RUNTIME, a localized field as an object{ pl, en }, but Payload's generated types declaredoc.slugasstring(the type does not know aboutallmode). Sotscreports a mismatch. Fix — a plain cast to the type the helper expects:const slugs = getLocalizedSlugs({ slugField: doc.slug as unknown as Record<string, unknown>, config, })This is not a hack — it bridges the static type (string) and the real runtime shape (object), which Payload's type generator does not model.
as unknown asis correct here, because TS does not knowallmode.
Language switcher (no 404)
// /pl/strona-glowna → click EN → /en/home (or /en if there is no translation)
const href = switchLocalePath({ slugs, targetLocale: 'en', config })
router.push(href)
switchLocalePath never returns undefined — no slug in a locale →
archive (when you pass prefix, e.g. /en/articles), otherwise /{locale} (root),
instead of a dead end on 404. Both functions take homeSlug (default 'home',
a string or a per-language map) and prefix (the archive page slugs per language →
/en/articles/my-post). buildLocalizedPath returns undefined when the slug
(or prefix) is missing in a language.
Others: getDefaultLocale(config), getLocaleDefinition(code, config),
negotiateLocale({ config, cookieLocale, acceptLanguage }),
matchAcceptLanguage(header, config), resolveLocalized(value, locale, fallback?)
(a localized field as a string or a map → text in the given language).
The pure path helpers (buildLocalizedPath, switchLocalePath, getLocalizedSlugs,
getLocaleCodes) are also in @intecion/ipal-kit/client.
Middleware — see separately
Locale negotiation + redirect on entry (domain.com → /pl): createProxy,
createLocaleMiddleware, DEFAULT_PROXY_MATCHER, DEFAULT_MIDDLEWARE_MATCHER —
available from @intecion/ipal-kit/next/middleware and from the main @intecion/ipal-kit.
See proxy in this section below.
Proxy (formerly middleware)
Next 16: the file is now called
proxy.ts, the functionproxy. The import from the plugin (@intecion/ipal-kit/next/middleware) is unchanged — it is the export subpath name, independent of the project's file name. Migration:npx @next/codemod@canary middleware-to-proxy .
Recommended (current):
createProxy— does locale negotiation, the root redirect, the language cookie with consent, and thex-locale/x-pathnameheaders:import { NextResponse } from 'next/server' import { createProxy } from '@intecion/ipal-kit' import { i18nConfig } from '@/i18n.config' export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) // markdown: GEO, content.md export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }Use the manual variant below only when you need your own logic in the proxy.
createProxy(i18nConfig, { … }) options:
| Option | Default | What it does |
|---|---|---|
NextResponse |
— (required) | injected from next/server (the plugin does not import it) |
markdown |
off | true = prefix /md, a string = a different one; paths under the prefix pass without a redirect, Accept: text/markdown → rewrite (content.md) |
exposeHeaders |
true |
request headers x-locale (language from the URL or defaultLocale) and x-pathname |
consentCategory |
'functional' |
consent category required to write the language cookie; 'necessary' = always write |
consentCookieName |
CONSENT_COOKIE |
consent cookie to read |
cookieName |
NEXT_LOCALE |
language cookie name |
policyVersion |
— (version stored in the consent cookie) | consent policy version required to write the language cookie (see below) |
The language cookie is set with path: '/', sameSite: 'lax' and no maxAge — it is
a session cookie; the browser deletes it on close (src/modules/i18n/createProxy.ts ~108).
The redirect is 307 (the default NextResponse.redirect).
// proxy.ts (client project) — the only logic is the wiring
import { NextResponse } from 'next/server'
import { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '@intecion/ipal-kit/next/middleware'
const i18nConfig = {
defaultLocale: 'pl',
locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }],
}
const localeMiddleware = createLocaleMiddleware({ config: i18nConfig })
export function proxy(req) {
const r = localeMiddleware(req)
if (r.type === 'next') return NextResponse.next()
const res = NextResponse.redirect(r.location)
if (r.cookie) res.cookies.set(r.cookie.name, r.cookie.value)
return res
}
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } // = DEFAULT_MIDDLEWARE_MATCHER, inline
Behavior:
- path with a locale (
/pl/...) → pass through - root or a path without a locale (
/,/o-nas) → redirect to/{locale}..., locale from: cookie → Accept-Language → default - the chosen locale is saved in a cookie (
LOCALE_COOKIE_NAME)
DEFAULT_MIDDLEWARE_MATCHER excludes api, admin, _next, static files.
The admin prefix is hard-coded — with a custom adminRoute (e.g. /its) add
it to the matcher ('/((?!api|its|_next|.*\\..*).*)'), otherwise the proxy redirects the admin panel
to /pl/its.
Locale cookie and consent (GDPR)
The language choice is saved in the NEXT_LOCALE cookie (a Next.js convention —
compatible with other i18n libraries that read the active locale). But
writing it requires consent: it is a functional category cookie, so:
- Write ONLY with consent. The middleware writes
NEXT_LOCALEonly when the user has consented to the functional category (mayPersistLocalechecks consent). Without consent the language works per request (negotiated from Accept-Language), but is not persisted. The proxy does not know the policy version set in the admin panel, so consent counts in the version it was saved with (after you bump the version, the language is still saved). To require a version:createLocaleMiddleware({ policyVersion })/createProxy(config, { policyVersion, … }). - Cleanup after consent is withdrawn. When the user withdraws functional consent,
the
NEXT_LOCALEcookie is deleted automatically (consent knows this cookie throughDEFAULT_COOKIE_MAP— see consent.md).
The cookie name is one constant, LOCALE_COOKIE_NAME (modules/i18n/negotiateLocale),
which propagates to the middleware and the consent cleanup. You can override it in
createLocaleMiddleware({ cookieName }), but the default NEXT_LOCALE is
recommended (interop).
Locale negotiation order
- The
NEXT_LOCALEcookie (if present — i.e. a choice was made with consent) - The
Accept-Languageheader (browser preferences) defaultLocalefrom the config
Visiting / → negotiation → redirect to /pl (or the negotiation result).
Changing the language (URL /en differs from the cookie) → the new choice is saved (with consent).
Migration from the old name: the cookie used to be called
ipal-locale. After the switch toNEXT_LOCALE, users with the old cookie go through negotiation once more (the old cookie is ignored). One-off, no effect on new projects.
Single-language site (no /pl prefix)
When a project has ONE language, URLs have no locale prefix: /o-nas, not
/pl/o-nas. The plugin detects this automatically — one locale in the config = single-language
mode. The helpers (buildLocalizedPath, hreflang, middleware) adapt
by themselves:
- buildLocalizedPath →
/o-nas(no/pl), home →/ - buildHreflangAlternates → empty (one language = no language alternates)
- localeMiddleware → pass-through (no
/→/plredirect, no negotiation) - canonical →
https://klient.pl/o-nas(no prefix)
Config — one locale
// i18n.config.ts
export const i18nConfig = {
locales: [{ code: 'pl', label: 'Polski' }], // ONE locale
defaultLocale: 'pl',
}
Folder structure — NO [locale]
This is the key difference. A single-language project has NO [locale] folder:
# SINGLE-LANGUAGE (no [locale])
app/(frontend)/
layout.tsx # locale fixed from the config, not from params
not-found.tsx
[[...slug]]/page.tsx # /o-nas, /kontakt
# MULTI-LANGUAGE (with [locale]) — for comparison
app/(frontend)/[locale]/
layout.tsx # locale from params
[[...slug]]/page.tsx # /pl/o-nas, /en/about
Layout, page, 404, Markdown — same helpers, no [locale]
// app/(frontend)/layout.tsx
import { i18nConfig } from '@/i18n.config'
export default async function Layout({ children }: { children: React.ReactNode }) {
const locale = i18nConfig.defaultLocale // fixed, not from params
return (
<html lang={locale}><body>
<SiteProviders shell={await getSiteShell(locale)} logEndpoint="/api/ipal/consent">{children}</SiteProviders>
</body></html>
)
}
// app/(frontend)/[[...slug]]/page.tsx — createPageRoute takes the language from the config when params has none
export const revalidate = 3600
const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect })
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams // returns { slug } without locale
// app/(frontend)/not-found.tsx (+ notFoundView.ts with a server action — pages.md)
export default createNotFoundPage(content, { load: loadNotFoundView })
// app/md/[[...slug]]/route.ts — NO [locale]: /md = home page, /md/kontakt = contact
export { markdownRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'
Links (resolveLink, resolveNav, getSystemLinks), sitemap, canonical, llms.txt and MCP produce URLs
without /pl by themselves — the number of languages in i18n.config.ts decides, not the folder structure.
(The md/[locale]/[[...slug]] route on a single-language site also serves subpages, but not /md —
hence md/[[...slug]] here.)
Middleware/proxy — a single-language site barely needs it
For one locale the middleware is pass-through (it redirects nothing). You can skip it or keep it — the plugin detects 1 locale and lets everything through anyway. No language switcher (one language), no NEXT_LOCALE cookie (nothing to remember).
Moving from single- to multi-language (later)
The number of languages in i18n.config.ts decides the prefix: one language = URLs without /pl (links,
sitemap, canonical), two or more = with the prefix. With one language, do not create the [locale]
structure in advance — the plugin would generate /kontakt links while pages live under /pl/kontakt.
When the client adds a second language:
- add the language to
i18n.config.ts(andlocalizationin Payload viaipalKit), - move
app/(frontend)/*toapp/(frontend)/[locale]/, andapp/md/[[...slug]]toapp/md/[locale]/[[...slug]], - the layout takes
localefromparams(PROGRAMISTA §2.8) —createPageRoute/createNotFoundPageunchanged, - translate slugs and content in the admin panel.
Links, sitemap, hreflang and canonical switch by themselves. The proxy redirects old URLs (
/kontakt) to/pl/kontakt, so links from Google and business listings keep working.
Language switcher without 404 (AlternateLinks + LanguageSwitcher)
When the slug differs per language (/pl/uslugi/karne vs /en/services/criminal),
a naive switcher (swapping the prefix /pl → /en) leads to a 404. The plugin
solves this with a context of alternate URLs.
How it works
- AlternateLinksProvider in the layout — holds the current page's URLs per language
- AlternateLinksUpdater on every page — reports its alternate URLs (the RSC page computes them from resolveRoute/getLocalizedSlugs)
- LanguageSwitcher — links to the correct URLs from the context
Wiring
// layout.tsx
import { AlternateLinksProvider } from '@intecion/ipal-kit/client'
<AlternateLinksProvider>{children}</AlternateLinksProvider>
// page.tsx (RSC) — compute alternates from routing
import { AlternateLinksUpdater } from '@intecion/ipal-kit/client'
const alternates = { pl: '/pl/uslugi/karne', en: '/en/services/criminal' }
return <>
<AlternateLinksUpdater links={alternates} />
{/* content */}
</>
// header (client) — switcher, headless, classNames like CookieBanner
import { LanguageSwitcher } from '@intecion/ipal-kit/client'
<LanguageSwitcher
config={i18nConfig}
currentLocale={locale}
classNames={{ root: '...', trigger: '...', menu: '...', item: '...', itemActive: '...' }}
/>
LanguageSwitcher has NO styles (classNames) — not variant="light|dark", so that it
fits any project design. A locale with no known alternate URL →
falls back to the root /{code}.
renderLabel needs a client wrapper. LanguageSwitcher is a client component and renderLabel is a
function; a server component (a header rendered on the server) cannot pass a function to a client
component — next build fails ("Functions cannot be passed directly to Client Components"). Put the
switcher with its renderLabel in a small client file of your own and render that from the server header:
// src/components/layout/LocaleSwitcher.tsx — a client component of your own
'use client'
import type { I18nConfig } from '@intecion/ipal-kit'
import { LanguageSwitcher } from '@intecion/ipal-kit/client'
export function LocaleSwitcher({ config, locale }: { config: I18nConfig; locale: string }) {
return (
<LanguageSwitcher
classNames={{ root: 'relative', trigger: '…', menu: '…', item: '…', itemActive: '…' }}
config={config}
currentLocale={locale}
renderLabel={(l) => l.code.toUpperCase()}
/>
)
}
// header.tsx (server): <LocaleSwitcher config={i18nConfig} locale={locale} />
Without renderLabel (the config labels) the server header can render LanguageSwitcher directly.
Where the page gets alternates: the RSC page already resolves the route (resolveRoute); from the same source compute the slugs per language (getLocalizedSlugs/buildLocalizedPath) and pass them to AlternateLinksUpdater. This removes the custom AlternateLinksContext (~150 lines) copied between projects.
Custom switcher (different markup than LanguageSwitcher): useAlternateLinks() (/client) returns
{ [locale]: url } for the current page; useSetAlternateLinks() is the setter used by
AlternateLinksUpdater (usually not needed in a project).
Next matcher — MUST be an inline literal
Next.js analyzes config.matcher STATICALLY (AST) — it must be an array literal
in the proxy/middleware file, not an import/variable. Even though the plugin exports
DEFAULT_PROXY_MATCHER, Next may not recognize it as an import. Safe:
// proxy.ts — matcher INLINE (not an import)
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
Use DEFAULT_PROXY_MATCHER as a reference value, but if Next complains
about the matcher — paste it inline. This is a Next limitation, not a plugin one.
Admin panel languages and texts
The site's content languages (i18n.locales) and the admin panel's language are
separate. The panel's language is what each user picks in Account → Language; until they pick one,
Payload takes the browser's language (English or Polish), else i18n.fallbackLanguage (Payload's
default en). An English browser therefore gets an English panel — 2FA screens included — on a
Polish site; set i18n.fallbackLanguage: 'pl' in your config to change the last step.
-
Default: when the project's
buildConfighas noi18n.supportedLanguages, ipal-kit sets English and Polish. A project that sets its own list keeps it, untouched:import { en } from 'payload/i18n/en' import { de } from 'payload/i18n/de' export default buildConfig({ i18n: { supportedLanguages: { en, de } }, /* … */ }) -
Field and global texts the plugin ships (labels, descriptions, options, tabs, groups) are
{ en, pl }objects (typeAdminText). Change one through the override options —globalOverrides,collectionOverrides— like any other field setting. -
Component texts (statistics view, test e-mail, integration alerts, cookie scan…) live in
adminTexts({ en: {…}, pl: {…} }) and are read through Payload's translations under theipalnamespace. Override any key per language; your value wins:export default buildConfig({ i18n: { translations: { pl: { ipal: { statsHeading: 'Ruch na stronie' } } } }, })A language the plugin has no texts for (e.g.
de) gets the English ones until you add yours. -
Building blocks for your own admin components:
ipalT(t, key, vars)reads a plugin text through Payload'st;formatNumber(n, language)andformatDateTime(iso, language, timeZone?)format in the admin language;defineTexts({ en, pl })declares a text set whose Polish keys must match the English ones;ADMIN_LANGUAGESlists the plugin's languages;applyAdminI18n(config)is the config step itself (already applied byipalKit). -
Browser-tab title of a custom admin view: Payload takes a view's
meta.titleas one plain string and never translates it (its custom-view metadata ignoresi18n), so the server-rendered title stays in that one language. Render<DocumentTitle title={…} />(@intecion/ipal-kit/admin) in the view with the translated title; after the page loads the tab follows the admin language.adminDocumentTitle(title, config.admin.meta.titleSuffix)builds the same "Title - Suffix" Payload would. The statistics view does this already: its tab reads Statystyki in the Polish panel. -
Wording rules for every label you add: dev/admin-ux.md.
-
Verify: switch Account → Language to Polski — every plugin global, collection and view reads in Polish;
pnpm testrunstest/adminUx.test.tsin the plugin.
Turn off, override, extend
i18nis required — the module cannot be turned off; one language = mode without the/plprefix.config.localizationis currently always overridden fromi18n(your ownlocalizationin payload.config does not survive);fallback: falseturns off Payload's fallback.- Proxy:
createProxywith options (consentCategory,cookieName,exposeHeaders,markdown,policyVersion) or your own proxy oncreateLocaleMiddleware+negotiateLocale/matchAcceptLanguage. - Switcher:
LanguageSwitcher(classNames,renderLabel— only from a client component: wrap it, see "Language switcher without 404") or your own onuseAlternateLinks(). - Paths:
buildLocalizedPath/switchLocalePathwithhomeSlugandprefix— for your own link helpers. - Admin languages: your own
i18n.supportedLanguageswins over the plugin's en + pl default; component texts viai18n.translations.<lang>.ipal.<key>.