Files
ipal-kit/docs/i18n.md
T
Radosław SmolińskiandClaude Opus 5.5 2d9f3e15d4 Docs in English (part 1), seeding guide, Coolify deployment
- Translate to English every doc the code branches did not touch: AGENT.md,
  developer guide, vibe, CHANGELOG, docs index, module pages, all skills
  except ipal-seo-check (14 pages follow after the security/SEO merge).
  Placeholder marker is now [TO FILL: …]; skill resources renamed to
  section-code.md / nav-code.md. AGENT.md and the ipal-skills pointer
  block say the docs are in English.
- docs/seeding.md: create-only, natural keys, never delete, no users or
  secrets, empty-field globals, fallbackLocale: false, dry run, backup and
  restore, production update guard, seeds vs migrations, Coolify Terminal.
  Seed templates gain --dry-run, the SEED_UPDATE production guard
  (IPAL_SEED_ALLOW_PROD_UPDATE), skip of edited records and a summary.
  "Seeding on production" rule block in AGENT.md.
- Coolify is the single deployment path (deployment, env, developer guide,
  ipal-setup): build vs runtime env, migrations on container start
  (prodMigrations), health check and rolling updates, rollback, backups and
  restore, DNS/Let's Encrypt/CAA. R2: custom domain needs a Cloudflare zone;
  default is media served by the app (R2_PUBLIC_URL empty).
- docsConsistency: no Polish prose outside code/quoted data (pending pages
  listed); IPAL_* names may also be read by shipped skill templates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:39:03 +02:00

381 lines
17 KiB
Markdown

# i18n
Localization: locale config for Payload, language negotiation
(cookie / Accept-Language / default), locale-aware path building,
language switching without 404.
## Config (payload.config.ts)
```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: false` and write only what they set
(`context: { ipalSkipAutoFill: true }` — seo.md); check data you change on a database copy first,
- `fallback: false` also 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.
```ts
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
```ts
// 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
> declare `doc.slug` as `string` (the type does not know about `all` mode). So `tsc`
> reports a mismatch. Fix — a plain cast to the type the helper
> expects:
> ```ts
> 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 as` is correct here, because TS does not know `all` mode.
### Language switcher (no 404)
```ts
// /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](#proxy-formerly-middleware) below.
## Proxy (formerly middleware)
> **Next 16:** the file is now called `proxy.ts`, the function `proxy`. 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 the `x-locale` / `x-pathname` headers:
> ```ts
> 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 |
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` ~106).
The redirect is 307 (the default `NextResponse.redirect`).
```ts
// 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_LOCALE` only when
the user has consented to the functional category (`mayPersistLocale` checks
consent). Without consent the language works per request (negotiated from Accept-Language),
but is not persisted.
- **Cleanup after consent is withdrawn.** When the user withdraws functional consent,
the `NEXT_LOCALE` cookie is deleted automatically (consent knows this cookie through
`DEFAULT_COOKIE_MAP` — see [consent.md](./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
1. The `NEXT_LOCALE` cookie (if present — i.e. a choice was made with consent)
2. The `Accept-Language` header (browser preferences)
3. `defaultLocale` from 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 to `NEXT_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 `/` → `/pl` redirect, no negotiation)
- **canonical** → `https://klient.pl/o-nas` (no prefix)
### Config — one locale
```ts
// 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]`
```tsx
// 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:
1. add the language to `i18n.config.ts` (and `localization` in Payload via `ipalKit`),
2. move `app/(frontend)/*` to `app/(frontend)/[locale]/`, and `app/md/[[...slug]]` to `app/md/[locale]/[[...slug]]`,
3. the layout takes `locale` from `params` (PROGRAMISTA §2.8) — `createPageRoute` / `createNotFoundPage` unchanged,
4. 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
1. **AlternateLinksProvider** in the layout — holds the current page's URLs per language
2. **AlternateLinksUpdater** on every page — reports its alternate URLs
(the RSC page computes them from resolveRoute/getLocalizedSlugs)
3. **LanguageSwitcher** — links to the correct URLs from the context
### Wiring
```tsx
// 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}`.
> **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:
```ts
// 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.
## Turn off, override, extend
- `i18n` is required — the module cannot be turned off; one language = mode without the `/pl` prefix.
- `config.localization` is currently always overridden from `i18n` (your own `localization` in payload.config does not survive); `fallback: false` turns off Payload's fallback.
- Proxy: `createProxy` with options (`consentCategory`, `cookieName`, `exposeHeaders`, `markdown`) or your own proxy on `createLocaleMiddleware` + `negotiateLocale` / `matchAcceptLanguage`.
- Switcher: `LanguageSwitcher` (`classNames`, `renderLabel`) or your own on `useAlternateLinks()`.
- Paths: `buildLocalizedPath` / `switchLocalePath` with `homeSlug` and `prefix` — for your own link helpers.