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]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
6e3979bae6
commit
2d9f3e15d4
+182
-182
@@ -1,8 +1,8 @@
|
||||
# i18n
|
||||
|
||||
Lokalizacja: konfiguracja locali dla Payload, negocjacja języka
|
||||
(cookie / Accept-Language / default), budowanie ścieżek locale-aware,
|
||||
przełączanie języka bez 404.
|
||||
Localization: locale config for Payload, language negotiation
|
||||
(cookie / Accept-Language / default), locale-aware path building,
|
||||
language switching without 404.
|
||||
|
||||
## Config (payload.config.ts)
|
||||
|
||||
@@ -15,37 +15,37 @@ ipalKit({
|
||||
{ code: 'en', label: 'English' },
|
||||
// { code: 'ar', label: 'العربية', rtl: true },
|
||||
],
|
||||
// fallback: true, // domyślnie true
|
||||
// fallback: true, // default true
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
| Pole | Domyślnie | Co robi |
|
||||
| Field | Default | What it does |
|
||||
|---|---|---|
|
||||
| `defaultLocale` | — (wymagane) | język domyślny; musi być na liście `locales` |
|
||||
| `locales` | — (wymagane, min. 1) | `{ code, label, rtl? }`; `code` w formacie `pl`, `en`, `pt-BR` |
|
||||
| `fallback` | `true` | `localization.fallback` Payloada (patrz niżej) |
|
||||
| `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) |
|
||||
|
||||
Opcja `i18n` jest **wymagana** (typ `I18nConfig`). Plugin ustawia `config.localization`
|
||||
z tego (nadpisując własne `localization` projektu). Walidacja jest eager — już przy
|
||||
wywołaniu `ipalKit()`, także z `enabled: false`: pusta lista, brak `code`/`label`,
|
||||
duplikaty kodów, `defaultLocale` spoza listy, zły format kodu → błąd `[ipal] i18n: ...`.
|
||||
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` a zapis.** Odczyt w języku bez wartości daje wartość języka domyślnego —
|
||||
i **zapis dokumentu utrwala ją**: zapis strony (w panelu albo `payload.update`) w dowolnym
|
||||
języku zapisuje tekst PL w polach lokalizowanych, które w EN/DE były puste (np. pusty
|
||||
`subheading` bloku dostaje polski). Skutki: niewidoczne braki tłumaczeń stają się polskim
|
||||
tekstem na stronie EN/DE. Dlatego:
|
||||
- tłumacz każde pole w każdym języku (nie licz na fallback),
|
||||
- skrypty migracji/seedów czytają z `fallbackLocale: false` i zapisują tylko to, co ustawiają
|
||||
(`context: { ipalSkipAutoFill: true }` — seo.md); dane do zmiany najpierw sprawdź na kopii bazy,
|
||||
- `fallback: false` wyłącza i odczyt z języka domyślnego (puste pola na stronie EN/DE) —
|
||||
świadoma decyzja projektu.
|
||||
**`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 — helpery
|
||||
## Front end — helpers
|
||||
|
||||
Wszystkie helpery są czyste (przyjmują config jako argument). Trzymaj swój
|
||||
`i18nConfig` w jednym miejscu i importuj gdzie trzeba.
|
||||
All helpers are pure (they take the config as an argument). Keep your
|
||||
`i18nConfig` in one place and import it where needed.
|
||||
|
||||
```ts
|
||||
import {
|
||||
@@ -60,72 +60,72 @@ getLocaleCodes(config) // ['pl', 'en']
|
||||
isValidLocale('de', config) // false
|
||||
```
|
||||
|
||||
### Budowanie ścieżek
|
||||
### Building paths
|
||||
|
||||
```ts
|
||||
// dokument pobrany z locale:'all' → slug to mapa { pl, en }
|
||||
// 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'
|
||||
// home slug ('home') zwija się do roota:
|
||||
// the home slug ('home') collapses to the root:
|
||||
buildLocalizedPath({ slugs: { en: 'home' }, locale: 'en', config }) // '/en'
|
||||
```
|
||||
|
||||
> **Pułapka typu (TypeScript):** przy `locale: 'all'` Payload w RUNTIME zwraca
|
||||
> zlokalizowane pole jako obiekt `{ pl, en }`, ale wygenerowane typy Payloada
|
||||
> deklarują `doc.slug` jako `string` (typ nie odróżnia trybu `all`). `tsc`
|
||||
> zgłosi więc niezgodność. Rozwiązanie — czyste rzutowanie na oczekiwany przez
|
||||
> helper typ:
|
||||
> **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,
|
||||
> })
|
||||
> ```
|
||||
> To nie hack — to pomost między statycznym typem (string) a rzeczywistym
|
||||
> kształtem runtime (obiekt), którego generator typów Payloada nie modeluje.
|
||||
> `as unknown as` jest tu poprawne, bo TS nie zna trybu `all`.
|
||||
> 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.
|
||||
|
||||
### Przełącznik języka (bez 404)
|
||||
### Language switcher (no 404)
|
||||
|
||||
```ts
|
||||
// /pl/strona-glowna → klik EN → /en/home (albo /en jeśli brak tłumaczenia)
|
||||
// /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` nigdy nie zwraca undefined — brak slug w danym locale →
|
||||
archiwum (gdy podasz `prefix`, np. `/en/articles`), inaczej `/{locale}` (root),
|
||||
zamiast dead-endu na 404. Obie funkcje przyjmują `homeSlug` (domyślnie `'home'`,
|
||||
string albo mapa per język) i `prefix` (slugi strony-archiwum per język →
|
||||
`/en/articles/my-post`). `buildLocalizedPath` zwraca `undefined`, gdy brak sluga
|
||||
(albo prefiksu) w danym języku.
|
||||
`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.
|
||||
|
||||
Pozostałe: `getDefaultLocale(config)`, `getLocaleDefinition(code, config)`,
|
||||
Others: `getDefaultLocale(config)`, `getLocaleDefinition(code, config)`,
|
||||
`negotiateLocale({ config, cookieLocale, acceptLanguage })`,
|
||||
`matchAcceptLanguage(header, config)`, `resolveLocalized(value, locale, fallback?)`
|
||||
(pole lokalizowane jako string albo mapa → tekst w danym języku).
|
||||
Czyste helpery ścieżek (`buildLocalizedPath`, `switchLocalePath`, `getLocalizedSlugs`,
|
||||
`getLocaleCodes`) są też w `@intecion/ipal-kit/client`.
|
||||
(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 — patrz osobno
|
||||
## Middleware — see separately
|
||||
|
||||
Negocjacja locale + redirect na wejściu (`domena.com` → `/pl`): `createProxy`,
|
||||
Locale negotiation + redirect on entry (`domain.com` → `/pl`): `createProxy`,
|
||||
`createLocaleMiddleware`, `DEFAULT_PROXY_MATCHER`, `DEFAULT_MIDDLEWARE_MATCHER` —
|
||||
dostępne z `@intecion/ipal-kit/next/middleware` i z głównego `@intecion/ipal-kit`.
|
||||
Zobacz [proxy w tej sekcji](#proxy-dawniej-middleware) niżej.
|
||||
available from `@intecion/ipal-kit/next/middleware` and from the main `@intecion/ipal-kit`.
|
||||
See [proxy in this section](#proxy-formerly-middleware) below.
|
||||
|
||||
## Proxy (dawniej middleware)
|
||||
## Proxy (formerly middleware)
|
||||
|
||||
> **Next 16:** plik nazywa się teraz `proxy.ts`, funkcja `proxy`. Import z
|
||||
> pluginu (`@intecion/ipal-kit/next/middleware`) bez zmian — to nazwa subpath
|
||||
> eksportu, niezależna od nazwy pliku projektu. Migracja:
|
||||
> **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 .`
|
||||
|
||||
> **Zalecane (aktualne): `createProxy`** — robi negocjację locale, redirect
|
||||
> roota, cookie języka za zgodą i nagłówki `x-locale` / `x-pathname`:
|
||||
> **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'
|
||||
@@ -133,25 +133,25 @@ Zobacz [proxy w tej sekcji](#proxy-dawniej-middleware) niżej.
|
||||
> export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true }) // markdown: GEO, content.md
|
||||
> export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
|
||||
> ```
|
||||
> Ręczny wariant poniżej tylko gdy potrzebujesz własnej logiki w proxy.
|
||||
> Use the manual variant below only when you need your own logic in the proxy.
|
||||
|
||||
Opcje `createProxy(i18nConfig, { … })`:
|
||||
`createProxy(i18nConfig, { … })` options:
|
||||
|
||||
| Opcja | Domyślnie | Co robi |
|
||||
| Option | Default | What it does |
|
||||
|---|---|---|
|
||||
| `NextResponse` | — (wymagane) | wstrzykiwany z `next/server` (plugin go nie importuje) |
|
||||
| `markdown` | wył. | `true` = prefiks `/md`, string = inny; ścieżki pod prefiksem przechodzą bez redirectu, `Accept: text/markdown` → rewrite (content.md) |
|
||||
| `exposeHeaders` | `true` | nagłówki żądania `x-locale` (język z URL albo `defaultLocale`) i `x-pathname` |
|
||||
| `consentCategory` | `'functional'` | kategoria zgody wymagana do zapisu cookie języka; `'necessary'` = zapisuj zawsze |
|
||||
| `consentCookieName` | `CONSENT_COOKIE` | cookie zgody do odczytu |
|
||||
| `cookieName` | `NEXT_LOCALE` | nazwa cookie języka |
|
||||
| `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 |
|
||||
|
||||
Cookie języka jest ustawiane z `path: '/'`, `sameSite: 'lax'` i **bez `maxAge`** — to
|
||||
cookie sesyjne, przeglądarka usuwa je po zamknięciu (`src/modules/i18n/createProxy.ts` ~106).
|
||||
Redirect to 307 (domyślny `NextResponse.redirect`).
|
||||
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 (projekt klienta) — jedyna logika to podłączenie
|
||||
// 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'
|
||||
|
||||
@@ -172,95 +172,95 @@ export function proxy(req) {
|
||||
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } // = DEFAULT_MIDDLEWARE_MATCHER, inline
|
||||
```
|
||||
|
||||
Zachowanie:
|
||||
- ścieżka z locale (`/pl/...`) → przepuść
|
||||
- root albo ścieżka bez locale (`/`, `/o-nas`) → redirect na `/{locale}...`,
|
||||
locale z: cookie → Accept-Language → default
|
||||
- wybrany locale zapisany w cookie (`LOCALE_COOKIE_NAME`)
|
||||
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` wyklucza `api`, `admin`, `_next`, pliki statyczne.
|
||||
Prefiks `admin` jest wpisany na sztywno — przy własnym `adminRoute` (np. `/its`) dopisz
|
||||
go do matchera (`'/((?!api|its|_next|.*\\..*).*)'`), inaczej proxy przekieruje panel
|
||||
na `/pl/its`.
|
||||
`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`.
|
||||
|
||||
## Cookie locale a zgoda (RODO)
|
||||
## Locale cookie and consent (GDPR)
|
||||
|
||||
Wybór języka zapisywany jest w cookie **`NEXT_LOCALE`** (konwencja Next.js —
|
||||
kompatybilna z innymi bibliotekami i18n, które czytają aktywny locale). Ale
|
||||
zapis podlega zgodzie: to cookie kategorii **functional**, więc:
|
||||
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:
|
||||
|
||||
- **Zapis TYLKO za zgodą.** Middleware zapisuje `NEXT_LOCALE` jedynie, gdy
|
||||
użytkownik zgodził się na kategorię functional (`mayPersistLocale` sprawdza
|
||||
zgodę). Bez zgody język działa per żądanie (negocjacja z Accept-Language),
|
||||
ale nie jest utrwalany.
|
||||
- **Sprzątanie po cofnięciu zgody.** Gdy użytkownik cofnie zgodę na functional,
|
||||
cookie `NEXT_LOCALE` jest usuwane automatycznie (consent zna tę cookie przez
|
||||
`DEFAULT_COOKIE_MAP` — patrz [consent.md](./consent.md)).
|
||||
- **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)).
|
||||
|
||||
Nazwa cookie to jedna stała `LOCALE_COOKIE_NAME` (`modules/i18n/negotiateLocale`),
|
||||
propagująca do middleware i sprzątania consent. Można nadpisać w
|
||||
`createLocaleMiddleware({ cookieName })`, ale domyślnie `NEXT_LOCALE` jest
|
||||
zalecane (interop).
|
||||
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).
|
||||
|
||||
### Kolejność negocjacji locale
|
||||
### Locale negotiation order
|
||||
|
||||
1. Cookie `NEXT_LOCALE` (jeśli jest — czyli był wybór za zgodą)
|
||||
2. Nagłówek `Accept-Language` (preferencje przeglądarki)
|
||||
3. `defaultLocale` z konfiguracji
|
||||
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
|
||||
|
||||
Wejście na `/` → negocjacja → redirect na `/pl` (albo wynik negocjacji).
|
||||
Zmiana języka (URL `/en` różny od cookie) → zapis nowego wyboru (za zgodą).
|
||||
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).
|
||||
|
||||
> **Migracja ze starej nazwy:** wcześniej cookie nazywało się `ipal-locale`.
|
||||
> Po zmianie na `NEXT_LOCALE` użytkownicy ze starą cookie przejdą raz ponowną
|
||||
> negocjację (stara cookie ignorowana). Jednorazowe, bez wpływu na nowe projekty.
|
||||
> **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.
|
||||
|
||||
## Strona jednojęzyczna (bez prefiksu /pl)
|
||||
## Single-language site (no /pl prefix)
|
||||
|
||||
Gdy projekt ma JEDEN język, adresy nie mają prefiksu locale: `/o-nas`, nie
|
||||
`/pl/o-nas`. Plugin wykrywa to automatycznie — **jeden locale w config = tryb
|
||||
jednojęzyczny**. Helpery (buildLocalizedPath, hreflang, middleware) dostosowują
|
||||
się same:
|
||||
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` (bez `/pl`), home → `/`
|
||||
- **buildHreflangAlternates** → pusto (jeden język = brak alternatyw językowych)
|
||||
- **localeMiddleware** → pass-through (brak przekierowania `/` → `/pl`, brak negocjacji)
|
||||
- **canonical** → `https://klient.pl/o-nas` (bez prefiksu)
|
||||
- **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 — jeden locale
|
||||
### Config — one locale
|
||||
|
||||
```ts
|
||||
// i18n.config.ts
|
||||
export const i18nConfig = {
|
||||
locales: [{ code: 'pl', label: 'Polski' }], // JEDEN locale
|
||||
locales: [{ code: 'pl', label: 'Polski' }], // ONE locale
|
||||
defaultLocale: 'pl',
|
||||
}
|
||||
```
|
||||
|
||||
### Struktura katalogów — BEZ [locale]
|
||||
### Folder structure — NO [locale]
|
||||
|
||||
To kluczowa różnica. Projekt jednojęzyczny NIE ma folderu `[locale]`:
|
||||
This is the key difference. A single-language project has NO `[locale]` folder:
|
||||
|
||||
```
|
||||
# JEDNOJĘZYCZNY (bez [locale])
|
||||
# SINGLE-LANGUAGE (no [locale])
|
||||
app/(frontend)/
|
||||
layout.tsx # locale stałe z config, nie z params
|
||||
layout.tsx # locale fixed from the config, not from params
|
||||
not-found.tsx
|
||||
[[...slug]]/page.tsx # /o-nas, /kontakt
|
||||
|
||||
# WIELOJĘZYCZNY (z [locale]) — dla porównania
|
||||
# MULTI-LANGUAGE (with [locale]) — for comparison
|
||||
app/(frontend)/[locale]/
|
||||
layout.tsx # locale z params
|
||||
layout.tsx # locale from params
|
||||
[[...slug]]/page.tsx # /pl/o-nas, /en/about
|
||||
```
|
||||
|
||||
### Layout, strona, 404, Markdown — te same helpery, bez `[locale]`
|
||||
### 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 // stałe, nie z params
|
||||
const locale = i18nConfig.defaultLocale // fixed, not from params
|
||||
return (
|
||||
<html lang={locale}><body>
|
||||
<SiteProviders shell={await getSiteShell(locale)} logEndpoint="/api/ipal/consent">{children}</SiteProviders>
|
||||
@@ -268,74 +268,74 @@ export default async function Layout({ children }: { children: React.ReactNode }
|
||||
)
|
||||
}
|
||||
|
||||
// app/(frontend)/[[...slug]]/page.tsx — createPageRoute bierze język z config, gdy nie ma go w params
|
||||
// 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 // zwraca { slug } bez locale
|
||||
export const generateStaticParams = route.generateStaticParams // returns { slug } without locale
|
||||
|
||||
// app/(frontend)/not-found.tsx (+ notFoundView.ts z server action — pages.md)
|
||||
// app/(frontend)/not-found.tsx (+ notFoundView.ts with a server action — pages.md)
|
||||
export default createNotFoundPage(content, { load: loadNotFoundView })
|
||||
|
||||
// app/md/[[...slug]]/route.ts — BEZ [locale]: /md = strona główna, /md/kontakt = kontakt
|
||||
// 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'
|
||||
```
|
||||
Linki (`resolveLink`, `resolveNav`, `getSystemLinks`), sitemap, canonical, llms.txt i MCP dają adresy
|
||||
bez `/pl` same — decyduje liczba języków w `i18n.config.ts`, nie struktura folderów.
|
||||
(Trasa `md/[locale]/[[...slug]]` na stronie jednojęzycznej też obsłuży podstrony, ale nie `/md` —
|
||||
dlatego tu `md/[[...slug]]`.)
|
||||
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 — jednojęzyczny prawie go nie potrzebuje
|
||||
### Middleware/proxy — a single-language site barely needs it
|
||||
|
||||
Dla jednego locale middleware jest pass-through (nic nie przekierowuje). Możesz
|
||||
go pominąć albo zostawić — plugin i tak wykryje 1 locale i przepuści. Bez
|
||||
przełącznika języka (jeden język), bez cookie NEXT_LOCALE (nie ma co pamiętać).
|
||||
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).
|
||||
|
||||
### Przejście jedno- → wielojęzyczny (później)
|
||||
### Moving from single- to multi-language (later)
|
||||
|
||||
O prefiksie decyduje **liczba języków w `i18n.config.ts`**: jeden język = adresy bez `/pl` (linki,
|
||||
sitemap, canonical), dwa i więcej = z prefiksem. Struktury `[locale]` przy jednym języku **nie
|
||||
zakładaj na zapas** — plugin generowałby linki `/kontakt`, a strony byłyby pod `/pl/kontakt`.
|
||||
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`.
|
||||
|
||||
Gdy klient doda drugi język:
|
||||
1. dodaj język do `i18n.config.ts` (i `localization` w Payload przez `ipalKit`),
|
||||
2. przenieś `app/(frontend)/*` do `app/(frontend)/[locale]/`, a `app/md/[[...slug]]` do `app/md/[locale]/[[...slug]]`,
|
||||
3. layout bierze `locale` z `params` (PROGRAMISTA §2.8) — `createPageRoute` / `createNotFoundPage` bez zmian,
|
||||
4. przetłumacz slugi i treści w panelu.
|
||||
Linki, sitemap, hreflang i canonical przełączą się same. Stare adresy (`/kontakt`) proxy przekieruje
|
||||
na `/pl/kontakt`, więc linki z Google i wizytówek dalej działają.
|
||||
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.
|
||||
|
||||
## Przełącznik języka bez 404 (AlternateLinks + LanguageSwitcher)
|
||||
## Language switcher without 404 (AlternateLinks + LanguageSwitcher)
|
||||
|
||||
Gdy slug różni się per język (`/pl/uslugi/karne` vs `/en/services/criminal`),
|
||||
naiwny przełącznik (podmiana prefiksu `/pl` → `/en`) prowadzi do 404. Plugin
|
||||
rozwiązuje to przez kontekst alternatywnych URL-i.
|
||||
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.
|
||||
|
||||
### Jak to działa
|
||||
### How it works
|
||||
|
||||
1. **AlternateLinksProvider** w layoutcie — trzyma URL-e per język bieżącej strony
|
||||
2. **AlternateLinksUpdater** na każdej stronie — zgłasza jej alternatywne URL-e
|
||||
(strona RSC wylicza je z resolveRoute/getLocalizedSlugs)
|
||||
3. **LanguageSwitcher** — linkuje do poprawnych URL-i z kontekstu
|
||||
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
|
||||
|
||||
### Wpięcie
|
||||
### Wiring
|
||||
|
||||
```tsx
|
||||
// layout.tsx
|
||||
import { AlternateLinksProvider } from '@intecion/ipal-kit/client'
|
||||
<AlternateLinksProvider>{children}</AlternateLinksProvider>
|
||||
|
||||
// page.tsx (RSC) — wylicz alternatywy z routingu
|
||||
// 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} />
|
||||
{/* treść */}
|
||||
{/* content */}
|
||||
</>
|
||||
|
||||
// header (client) — przełącznik, headless, classNames jak CookieBanner
|
||||
// header (client) — switcher, headless, classNames like CookieBanner
|
||||
import { LanguageSwitcher } from '@intecion/ipal-kit/client'
|
||||
<LanguageSwitcher
|
||||
config={i18nConfig}
|
||||
@@ -344,37 +344,37 @@ import { LanguageSwitcher } from '@intecion/ipal-kit/client'
|
||||
/>
|
||||
```
|
||||
|
||||
LanguageSwitcher jest BEZ stylów (classNames) — nie `variant="light|dark"`, żeby
|
||||
pasował do każdego designu projektu. Locale bez znanego alternatywnego URL →
|
||||
fallback na root `/{code}`.
|
||||
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}`.
|
||||
|
||||
> **Skąd alternates na stronie:** strona RSC już rozwiązuje trasę (resolveRoute);
|
||||
> z tego samego źródła wylicz slugi per język (getLocalizedSlugs/buildLocalizedPath)
|
||||
> i przekaż do AlternateLinksUpdater. To eliminuje własny AlternateLinksContext
|
||||
> (~150 linii) kopiowany w projektach.
|
||||
> **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.
|
||||
|
||||
Własny przełącznik (inny markup niż `LanguageSwitcher`): `useAlternateLinks()` (`/client`) zwraca
|
||||
`{ [locale]: url }` bieżącej strony; `useSetAlternateLinks()` to setter, którego używa
|
||||
`AlternateLinksUpdater` (zwykle niepotrzebny w projekcie).
|
||||
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 — MUSI być literałem inline
|
||||
## Next matcher — MUST be an inline literal
|
||||
|
||||
Next.js analizuje `config.matcher` STATYCZNIE (AST) — musi być literałem tablicy
|
||||
w pliku proxy/middleware, nie importem/zmienną. Mimo że plugin eksportuje
|
||||
`DEFAULT_PROXY_MATCHER`, Next może nie rozpoznać go jako importu. Bezpiecznie:
|
||||
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 (nie import)
|
||||
// proxy.ts — matcher INLINE (not an import)
|
||||
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
|
||||
```
|
||||
|
||||
`DEFAULT_PROXY_MATCHER` używaj jako referencji wartości, ale jeśli Next narzeka
|
||||
na matcher — wklej go inline. To ograniczenie Next, nie pluginu.
|
||||
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.
|
||||
|
||||
## Wyłączenie, nadpisanie, rozszerzenie
|
||||
## Turn off, override, extend
|
||||
|
||||
- `i18n` jest wymagane — modułu nie da się wyłączyć; jeden język = tryb bez prefiksu `/pl`.
|
||||
- `config.localization` jest obecnie zawsze nadpisywane z `i18n` (własne `localization` w payload.config nie przetrwa); `fallback: false` wyłącza fallback Payloada.
|
||||
- Proxy: `createProxy` z opcjami (`consentCategory`, `cookieName`, `exposeHeaders`, `markdown`) albo własne proxy na `createLocaleMiddleware` + `negotiateLocale` / `matchAcceptLanguage`.
|
||||
- Przełącznik: `LanguageSwitcher` (`classNames`, `renderLabel`) albo własny na `useAlternateLinks()`.
|
||||
- Ścieżki: `buildLocalizedPath` / `switchLocalePath` z `homeSlug` i `prefix` — do własnych helperów linków.
|
||||
- `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.
|
||||
|
||||
Reference in New Issue
Block a user