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:
Radosław Smoliński
2026-10-22 17:39:03 +02:00
co-authored by Claude Opus 5.5
parent 6e3979bae6
commit 2d9f3e15d4
47 changed files with 6102 additions and 5355 deletions
+188 -174
View File
@@ -1,28 +1,29 @@
# storage — media na Cloudflare R2
# storage — media on Cloudflare R2
Offload mediów (obrazy, pliki) do Cloudflare R2 zamiast lokalnego dysku. R2 jest
S3-kompatybilny; plugin dostarcza `buildR2Storage`, który czyta dane z `.env`
i konfiguruje adapter.
Offload media (images, files) to Cloudflare R2 instead of the local disk. R2 is
S3-compatible; the plugin provides `buildR2Storage`, which reads the settings from `.env`
and configures the adapter.
> **Storage to infrastruktura, nie treść.** Dane R2 (klucze, bucket) idą do
> `.env` — jak DATABASE_URI, PAYLOAD_SECRET, GRAPH_*. NIE do panelu (to sekrety
> agencyjne, wiążą się przy starcie, nie zmienia ich redaktor).
> **Storage is infrastructure, not content.** R2 settings (keys, bucket) go into
> `.env` — like DATABASE_URI, PAYLOAD_SECRET, GRAPH_*. NOT into the admin panel (they are agency
> secrets, bound at startup, the editor does not change them).
## Zmienne .env
## .env variables
Skąd wziąć wartości: Cloudflare → R2 → bucket (nazwa), Overview → S3 API (endpoint `https://<ACCOUNT_ID>.r2.cloudflarestorage.com`), Manage R2 API Tokens → „Object Read & Write” (para kluczy; secret widać raz). Wszystkie 4 zmienne → R2; brak którejś → dysk lokalny (częściowa konfiguracja = ostrzeżenie w logu).
Where to get the values: Cloudflare → R2 → bucket (name), Overview → S3 API (endpoint `https://<ACCOUNT_ID>.r2.cloudflarestorage.com`), Manage R2 API Tokens → "Object Read & Write" (a key pair; the secret is shown once). All 4 variables → R2; any missing → local disk (partial configuration = a warning in the log).
```bash
R2_BUCKET=nazwa-bucketa
R2_BUCKET=bucket-name
R2_ENDPOINT=https://<ACCOUNT_ID>.r2.cloudflarestorage.com
R2_ACCESS_KEY_ID=<access-key-id>
R2_SECRET_ACCESS_KEY=<secret-access-key>
R2_PUBLIC_URL= # empty = media served through the app (default); a media domain → see "Public access"
```
## Wpięcie (payload.config.ts)
## Wiring (payload.config.ts)
```bash
pnpm add @payloadcms/storage-s3 # opcjonalny peer pluginu; ta sama wersja co payload (pnpm.overrides)
pnpm add @payloadcms/storage-s3 # optional plugin peer; same version as payload (pnpm.overrides)
```
```ts
@@ -33,197 +34,210 @@ export default buildConfig({
// ...
plugins: [
ipalKit({ /* ... */ }),
buildR2Storage(['media'], { s3Storage }), // slugi kolekcji + WSTRZYKNIĘTY adapter
buildR2Storage(['media'], { s3Storage }), // collection slugs + the INJECTED adapter
],
})
```
`buildR2Storage` przyjmuje listę kolekcji upload (domyślnie `['media']`). Jeśli
masz więcej kolekcji plików: `buildR2Storage(['media', 'documents'], { s3Storage })`.
`buildR2Storage` takes a list of upload collections (default `['media']`). If
you have more file collections: `buildR2Storage(['media', 'documents'], { s3Storage })`.
**Adapter jest wstrzykiwany (od 1.8.1)** — plugin nie importuje
`@payloadcms/storage-s3`, bo to opcjonalna zależność: projekty na dysku lokalnym
jej nie instalują. Ten sam wzorzec co `payloadTotp` w 2FA i `NextResponse` w
proxy. Gdy env R2 jest ustawione, a `s3Storage` nie przekazano, start kończy się
czytelnym błędem (zamiast cichego zapisu mediów na dysk kontenera, który znika
przy redeployu). Starsze wywołanie `buildR2Storage(['media'])` bez adaptera
działa tylko bez env R2.
**The adapter is injected (since 1.8.1)** — the plugin does not import
`@payloadcms/storage-s3`, because it is an optional dependency: projects on local disk
don't install it. The same pattern as `payloadTotp` in 2FA and `NextResponse` in the
proxy. When the R2 env is set but `s3Storage` was not passed, startup ends with a
clear error (instead of silently writing media to the container disk, which disappears
on redeploy). The older call `buildR2Storage(['media'])` without an adapter
works only without the R2 env.
## Zachowanie (fallback)
## Behavior (fallback)
- **Wszystkie 4 zmienne** → media w R2.
- **Brak zmiennych** → fallback na lokalny dysk (dev działa bez R2, zero konfiguracji).
- **Część zmiennych** → ostrzeżenie w logu + fallback (częściowa konfiguracja =
pewnie pomyłka).
- **Tylko `R2_PUBLIC_URL`** (absolutny, poza produkcją) → **media tylko do odczytu** (1.12.2):
adresy plików z domeny mediów, upload i usuwanie zablokowane (403). Do lokalnego deva
podpiętego pod bazę produkcyjną — widać obrazy, a nic nie trafia do prawdziwego bucketa.
- **All 4 variables** → media in R2.
- **No variables** → fallback to local disk (dev works without R2, zero configuration).
- **Some of the variables** → a warning in the log + fallback (partial configuration =
probably a mistake).
- **Only `R2_PUBLIC_URL`** (absolute, outside production) → **read-only media** (1.12.2):
file URLs from the media domain, upload and delete blocked (403). For local dev
connected to the production database — you see images, and nothing reaches the real bucket.
**Import map nie zależy od env (1.12.2).** Gdy projekt wstrzykuje `s3Storage`, adapter jest
rejestrowany zawsze — bez R2 jako wyłączony (`enabled: false`, dysk lokalny). storage-s3 i tak
dopisuje wtedy swój `S3ClientUploadHandler` do import mapy, więc `pnpm dev` /
`generate:importmap` bez `R2_*` zapisuje ten sam `importMap.js` co produkcja. Do 1.12.1 dev bez
R2 usuwał ten wpis, a produkcyjny panel (z R2) renderował **pustą stronę** bez błędu w konsoli.
`ipal-audit` zgłasza import mapę bez handlera.
**The import map does not depend on env (1.12.2).** When the project injects `s3Storage`, the adapter is
always registered — without R2 as disabled (`enabled: false`, local disk). storage-s3 still
adds its `S3ClientUploadHandler` to the import map then, so `pnpm dev` /
`generate:importmap` without `R2_*` writes the same `importMap.js` as production. Up to 1.12.1, dev without
R2 removed that entry, and the production admin panel (with R2) rendered a **blank page** with no console error.
`ipal-audit` reports an import map without the handler.
To wzorzec „degrade gracefully" — jak mailAdapter, który wraca do SMTP, gdy brak
Graph. Projekt działa niezależnie od tego, czy R2 jest skonfigurowany.
This is the "degrade gracefully" pattern — like mailAdapter, which falls back to SMTP when there is no
Graph. The project works whether or not R2 is configured.
## Publiczny dostęp + custom domena (WAŻNE — krok po kroku)
## Public access — how media reach the browser (IMPORTANT)
R2 domyślnie prywatny. Upload zadziała, ale obrazy się NIE wyświetlą (403),
dopóki nie skonfigurujesz publicznego odczytu przez custom domenę. To proces
w Cloudflare (nie w kodzie), wieloetapowy — poniżej dokładnie.
R2 is private by default: the S3 endpoint (`<ACCOUNT_ID>.r2.cloudflarestorage.com`) accepts uploads but does not
serve files publicly. `R2_PUBLIC_URL` decides where the URLs Payload generates point:
### Dlaczego custom domena, nie „r2.dev"
| `R2_PUBLIC_URL` | Media URL | DNS / Cloudflare | Use |
|---|---|---|---|
| **empty (default)** | `/api/media/file/<name>` on the site's own domain — Payload streams the file from R2 | nothing | every project whose zone is on our DNS servers |
| `https://<media domain>` | `https://<media domain>/<name>` — straight from R2 via Cloudflare | the domain's zone in our Cloudflare account + bucket Custom Domain | media-heavy sites that need the CDN |
| `https://pub-….r2.dev` | r2.dev URL | none | dev/testing only — rate-limited, no cache |
R2 oferuje szybki publiczny URL `*.r2.dev`, ALE:
- jest rate-limitowany (nie do produkcji)
- nie przechodzi przez cache Cloudflare (brak CDN, wolniej, drożej)
- brzydki URL (nie Twoja domena)
**Why not `media.klient.pl`?** An R2 bucket Custom Domain must belong to a zone **in the same Cloudflare account**,
with full setup (nameservers at Cloudflare). A CNAME ("partial") setup for a zone kept on other DNS servers needs a
Business or Enterprise plan. Our clients' zones are on our own servers, so a subdomain of the client's domain
cannot be attached to the bucket. (A reverse proxy on the Coolify server, `media.klient.pl` → the bucket, is
possible but adds moving parts.) DNS checklist: deployment.md §6 row 9.
Dla produkcji ZAWSZE custom domena (np. `media.klient.pl`) — daje CDN, cache,
własny URL. r2.dev tylko do szybkiego testu.
### Default: media through the app (`R2_PUBLIC_URL` empty)
### Warunek wstępny: domena w Cloudflare
With all 4 R2 keys and no public URL, `buildR2Storage` gives the collections plain offload (`true`): files are
stored in R2, and Payload's file route `/api/media/file/<name>` (`/api/<slug>/file/<name>` for other upload
collections) reads them from the bucket. The stored URL is site-relative (our projects do not set `serverURL` in
`payload.config.ts`).
Custom domena dla R2 wymaga, żeby domena (albo subdomena) była zarządzana przez
Cloudflare (nameservery klienta wskazują na Cloudflare). Jeśli domena klienta
jest u innego rejestratora — trzeba ją najpierw dodać do Cloudflare (Add Site)
i przełączyć nameservery. Sama subdomena `media.klient.pl` wystarczy, jeśli
główna domena jest już w Cloudflare.
Requirements and consequences:
- **Public read on the upload collection** — the file route checks the collection's `read` access, and Payload's
default is "logged-in users only" → anonymous visitors (and next/image) get 403. Add
`access: { read: () => true }` to `Media` (and every other public upload collection).
- **Env validation** — `ipalEnvRules({ storage: true })` requires `R2_PUBLIC_URL` in production; make it optional:
### Krok po kroku — podpięcie custom domeny
```ts
assertEnv(
ipalEnvRules({ storage: true, ipHeader: true }).map((r) =>
r.name === 'R2_PUBLIC_URL' ? { ...r, required: false } : r,
),
)
```
- next/image treats the URLs as local images; CSP `img-src 'self'` already covers them; `MediaPreconnect` renders
nothing (same origin); the plugin's sitemap / JSON-LD helpers make relative image URLs absolute.
- Cost: every original file request passes through the app (bandwidth/CPU). Page images go through `/_next/image`,
whose optimized variants are cached (`minimumCacheTTL` 31 days, `buildImagesConfig`); heavy video/PDF traffic →
consider option 2.
1. **Cloudflare Dashboard → R2 → wybierz bucket**
2. Zakładka **Settings** → sekcja **Public access** → **Custom Domains**
3. **Connect Domain** → wpisz subdomenę, np. `media.klient.pl`
4. Cloudflare automatycznie doda rekord CNAME (bo domena jest w Cloudflare) i
wystawi certyfikat SSL. Poczekaj, aż status = **Active** (kilka minut).
5. Od tej chwili pliki są publiczne pod `https://media.klient.pl/<klucz-pliku>`.
Check: upload an image, its URL in the panel is `/api/media/file/<name>`;
`curl -sI https://klient.pl/api/media/file/<name>` → `200` (not 403) without being logged in.
### Krok: ustaw publiczny URL w projekcie
### Option: a media domain on Cloudflare (`R2_PUBLIC_URL` set)
Payload musi generować URL-e mediów wskazujące na custom domenę, nie na endpoint
S3. Dodaj zmienną i przekaż ją do adaptera:
For sites with heavy media: a separate domain whose zone is in our Cloudflare account (e.g. `klient-media.com`, or
a subdomain of one shared agency media domain). Gives the Cloudflare CDN, cache rules and no app traffic.
1. **Cloudflare Dashboard → R2 → pick the bucket**
2. **Settings** tab → **Public access** section → **Custom Domains**
3. **Connect Domain** → enter the domain, e.g. `media.klient-media.com` (its zone must be in this account)
4. Cloudflare adds the DNS record automatically and issues a certificate. Wait until the status = **Active**.
5. From then on files are public at `https://media.klient-media.com/<file-key>`.
Then set the URL in the project:
```bash
# .env
R2_PUBLIC_URL=https://media.klient.pl
# dev z rewrite /media → bucket: R2_PUBLIC_URL=/media (tylko poza produkcją; env.md)
# .env / Coolify
R2_PUBLIC_URL=https://media.klient-media.com
# dev with a /media → bucket rewrite: R2_PUBLIC_URL=/media (outside production only; env.md)
```
Adapter `buildR2Storage` czyta ją i ustawia jako bazowy URL mediów (jeśli
ustawiona). Bez niej Payload zwróci URL wskazujący na prywatny endpoint S3 →
403 na froncie. (Patrz aktualizacja buildR2Storage niżej.)
`buildR2Storage` passes it as `generateFileURL` → Payload stores `https://media.klient-media.com/<file>` URLs.
`buildImagesConfig`, `buildCsp({ r2Url })` and `MediaPreconnect` read the same variable.
### Weryfikacja
**Verification:** upload an image; its URL in the panel is `https://media.klient-media.com/...` (not
`/api/media/file/...`, not `*.r2.cloudflarestorage.com`); the URL opens in a browser (not 403); `<img src>` works.
1. Wgraj obraz w panelu (Media).
2. Sprawdź URL obrazu w panelu — powinien być `https://media.klient.pl/...`,
NIE `https://<account>.r2.cloudflarestorage.com/...`.
3. Otwórz URL w przeglądarce — obraz się pokazuje (nie 403).
4. Na froncie `<img src>` działa.
**403 despite a custom domain:** custom domain not **Active** yet (wait for the certificate), or created but not
connected to the bucket (bucket Settings → Custom Domains), or the URL in the panel still points elsewhere
(`R2_PUBLIC_URL` missing at runtime → redeploy).
### Częsty błąd: 403 mimo custom domeny
### Why not "r2.dev"
- **URL wskazuje na endpoint S3, nie custom domenę** → brakuje `R2_PUBLIC_URL`
albo adapter jej nie używa. Sprawdź URL w panelu.
- **Custom domena nie Active** → poczekaj na SSL/CNAME w Cloudflare.
- **Public access wyłączony** → w bucket Settings sprawdź, czy custom domena jest
podpięta (nie tylko utworzona).
The quick public URL `*.r2.dev` is rate-limited, does not go through the Cloudflare cache, and is not your
domain — use it only for a quick test, never in production.
Bez tego media wgrają się do R2, ale front pokaże 403. Konfiguracja domeny jest
po stronie Cloudflare, publiczny URL po stronie projektu (.env).
### Media caching on the media domain (Cache Rule — mandatory with option 2)
### Pamięć podręczna mediów (Cache Rule — obowiązkowo)
Files in R2 have no `Cache-Control` header: `@payloadcms/storage-s3` sets only
`ContentType` and `ACL` on upload, with no option for headers. Cloudflare then gives the browser the default **4 h** —
Lighthouse: "Use efficient cache lifetimes" (video, logo, backgrounds downloaded
again on every visit after 4 h). File names are stable (a new version = a new file from `normalizeFilename`),
so a long lifetime is safe.
Pliki w R2 nie mają nagłówka `Cache-Control`: `@payloadcms/storage-s3` przy wysyłce ustawia tylko
`ContentType` i `ACL`, bez opcji na nagłówki. Cloudflare daje wtedy przeglądarce domyślne **4 h** —
Lighthouse: „Używaj efektywnego czasu przechowywania w pamięci podręcznej” (wideo, logo, tła pobierane od
nowa przy każdej wizycie po 4 h). Nazwy plików są stałe (nowa wersja = nowy plik z `normalizeFilename`),
więc długi czas jest bezpieczny.
Cloudflare → strefa domeny → **Caching → Cache Rules → Create rule**:
- *When incoming requests match*: `Hostname` equals `media.klient.pl` (domena z `R2_PUBLIC_URL`);
Cloudflare → the media domain's zone → **Caching → Cache Rules → Create rule**:
- *When incoming requests match*: `Hostname` equals `media.klient-media.com` (the domain from `R2_PUBLIC_URL`);
- *Cache eligibility*: Eligible for cache;
- *Edge TTL*: Ignore cache-control header and use this TTL → **1 year**;
- *Browser TTL*: Override origin and use this TTL → **1 year**.
Sprawdzenie (po kilku minutach):
Check (after a few minutes):
```bash
curl -sI https://media.klient.pl/<plik> | grep -iE 'cache-control|cf-cache-status'
# cache-control: max-age=31536000 cf-cache-status: HIT (przy drugim zapytaniu)
curl -sI https://media.klient-media.com/<file> | grep -iE 'cache-control|cf-cache-status'
# cache-control: max-age=31536000 cf-cache-status: HIT (on the second request)
```
Podmiana pliku pod TĄ SAMĄ nazwą (rzadkie — panel nadaje nową) wymaga Caching → Purge → Custom (URL).
Replacing a file under THE SAME name (rare — the admin panel assigns a new one) needs Caching → Purge → Custom (URL).
## Migracja istniejących mediów
## Migrating existing media
Jeśli projekt miał media lokalnie i przełączasz na R2 — nowe uploady idą do R2,
ale STARE zostają na dysku (i znikną przy redeployu bez wolumenu). Przed
przełączeniem na produkcji przenieś istniejące pliki do bucketa (np. `rclone`
albo ręcznie przez R2 dashboard), inaczej stare obrazy znikną.
If the project had media locally and you switch to R2 — new uploads go to R2,
but the OLD ones stay on disk (and disappear on a redeploy without a volume). Before
switching in production, move the existing files to the bucket (e.g. `rclone`
or manually through the R2 dashboard), otherwise old images disappear.
## Weryfikacja
## Verification
```bash
# po wpięciu i ustawieniu .env:
# after wiring and setting .env:
pnpm dev
# wgraj obraz w panelu (Media) → sprawdź w Cloudflare R2, czy plik się pojawił
# upload an image in the admin panel (Media) → check in Cloudflare R2 that the file appeared
```
## Root subdomeny media zwraca 404 (to normalne)
## The media domain root returns 404 (this is normal — option 2 only)
`media.klient.pl/plik.jpg` → R2 zwraca plik. Ale `media.klient.pl/` (sam root,
bez pliku) → **404**, bo R2 nie ma obiektu pod rootem. To NORMALNE zachowanie
R2, nie błąd.
`media.klient-media.com/plik.jpg` → R2 returns the file. But `media.klient-media.com/` (the bare root,
no file) → **404**, because R2 has no object at the root. This is NORMAL R2
behavior, not an error.
Audyty SEO (Screaming Frog) czasem zgłaszają to 404 — bo crawler widzi URL-e
plików (`media.../logo.svg`) i próbuje roota. Ale:
- **NIE linkuj do samego roota** `media.klient.pl/` — tylko do plików. Kod nie
powinien nigdzie mieć `media.klient.pl/` bez nazwy pliku.
- Root media 404 **nie szkodzi SEO** głównej domeny (Google indeksuje klient.pl,
nie media.klient.pl). Nikt nie trafia na root media.
SEO audits (Screaming Frog) sometimes report this 404 — the crawler sees file
URLs (`media.../logo.svg`) and tries the root. But:
- **Do NOT link to the bare root** `media.klient-media.com/` — only to files. The code should
never have `media.klient-media.com/` without a file name.
- The media root 404 **does not hurt SEO** of the main domain (Google indexes klient.pl,
not media.klient-media.com). Nobody lands on the media root.
**Plugin tego nie naprawi** — subdomena media to serwis R2/Cloudflare, nie
aplikacja Next. Żądania do media.klient.pl nie docierają do Twojego kodu.
**The plugin will not fix this** — the media subdomain is an R2/Cloudflare service, not
the Next app. Requests to media.klient-media.com never reach your code.
Jeśli chcesz „czysto" w Search Console (opcjonalne): Cloudflare → Rules →
Redirect Rules → gdy hostname = `media.klient.pl` i path = `/` → 301 na
`klient.pl`. Jednorazowo w panelu CF. Ale to kosmetyka — root media 404 jest
nieszkodliwe.
If you want it "clean" in Search Console (optional): Cloudflare → Rules →
Redirect Rules → when hostname = `media.klient-media.com` and path = `/` → 301 to
`klient.pl`. A one-off in the CF dashboard. But it is cosmetic — the media root 404 is
harmless.
## Dev na lokalnym I na R2 (seedowanie podczas developmentu)
## Dev on local disk AND on R2 (seeding during development)
Fallback (brak zmiennych → lokalny dysk) oznacza, że **dev działa w obu trybach**:
The fallback (no variables → local disk) means that **dev works in both modes**:
- **Dev bez R2 w .env** → media na lokalnym dysku. Szybki start, zero konfiguracji.
- **Dev z R2 w .env** → media w R2 już podczas developmentu. Przydatne, gdy
seedujesz treść w devie i chcesz, żeby od razu lądowała w buckecie (np. wspólny
bucket dev, albo test realnego flow przed produkcją).
- **Dev without R2 in .env** → media on local disk. Quick start, zero configuration.
- **Dev with R2 in .env** → media in R2 already during development. Useful when
you seed content in dev and want it to land in the bucket right away (e.g. a shared
dev bucket, or testing the real flow before production).
Przełączasz trybem po prostu obecnością zmiennych R2 w `.env`. Ten sam kod,
`buildR2Storage` sam wykrywa. Nie musisz nic zmieniać w configu między trybami.
You switch modes simply by the presence of the R2 variables in `.env`. The same code;
`buildR2Storage` detects it by itself. You don't need to change anything in the config between modes.
> Jeśli seedujesz w devie do R2 — pamiętaj, że to realny bucket. Używaj osobnego
> bucketa dev (nie produkcyjnego), żeby nie mieszać danych testowych z realnymi.
> If you seed to R2 in dev — remember it is a real bucket. Use a separate
> dev bucket (not the production one), so test data does not mix with real data.
## Kolekcja Media — nazwy plików, za duże uploady, placeholdery
## The Media collection — file names, oversized uploads, placeholders
`normalizeFilenameHook`, `buildOptimizeUploadHook` / `buildOptimizeUploadField`,
`buildMediaPlaceholderHook` / `buildMediaPlaceholderField`, `mediaImageProps`, `videoProps`,
`MEDIA_SIZES` — opis w **[media.md](./media.md)**. Wszystkie hooki biegną przed warstwą
storage, więc działają tak samo na dysku lokalnym i w R2.
`MEDIA_SIZES` — described in **[media.md](./media.md)**. All hooks run before the storage
layer, so they work the same on local disk and in R2.
## Preconnect do domeny mediów (wydajność)
## Preconnect to the media domain (performance)
Komponent `MediaPreconnect` generuje `<link rel="preconnect">` + `dns-prefetch`
dla domeny mediów (R2_PUBLIC_URL) — przeglądarka nawiązuje połączenie TLS/DNS
z CDN zawczasu, zanim napotka pierwszy `<img>`. Zysk ~150–300 ms na pierwszym
obrazie.
The `MediaPreconnect` component generates `<link rel="preconnect">` + `dns-prefetch`
for the media domain (R2_PUBLIC_URL) — the browser opens the TLS/DNS connection
to the CDN in advance, before it meets the first `<img>`. Gain ~150–300 ms on the first
image.
```tsx
// layout.tsx — na GÓRZE <body>, NIE w jawnym <head>
// layout.tsx — at the TOP of <body>, NOT in an explicit <head>
import { MediaPreconnect } from '@intecion/ipal-kit/rsc'
<body className={...}>
@@ -232,44 +246,44 @@ import { MediaPreconnect } from '@intecion/ipal-kit/rsc'
</body>
```
> **NIE umieszczaj w jawnym `<head>`!** Sztywny `<head><MediaPreconnect/></head>`
> w layoutcie App Router wymusza przedwczesne zamknięcie head — zanim strona
> wygeneruje metadane — przez co title/canonical/hreflang lądują w `<body>`
> (crawlery ich nie widzą). React 19 sam hoistuje `<link rel="preconnect">` do
> `<head>`, więc renderowanie w `<body>` jest poprawne. Patrz seo.md (metadata w head).
> **Do NOT put it in an explicit `<head>`!** A hard-coded `<head><MediaPreconnect/></head>`
> in an App Router layout forces the head to close early — before the page
> generates its metadata — so title/canonical/hreflang end up in `<body>`
> (crawlers don't see them). React 19 hoists `<link rel="preconnect">` into
> `<head>` by itself, so rendering in `<body>` is correct. See seo.md (metadata in head).
Czyta domenę z **R2_PUBLIC_URL** (to samo źródło co buildR2Storage) — zero
hardkodu, jedno źródło prawdy. Gdy R2_PUBLIC_URL nie ustawione (lokalny dysk,
brak CDN) albo jest ścieżką (`/media`) → nie renderuje nic. `SiteProviders` wpina go sam
(`preconnect={false}` wyłącza) — ręcznie tylko przy własnym layoucie bez `SiteProviders`. Zmiana domeny mediów = zmiana jednej zmiennej
env, komponent podąża automatycznie.
It reads the domain from **R2_PUBLIC_URL** (the same source as buildR2Storage) — zero
hard-coding, one source of truth. When R2_PUBLIC_URL is not set (media through the app or local disk,
no CDN) or is a path (`/media`) → it renders nothing. `SiteProviders` wires it by itself
(`preconnect={false}` turns it off) — wire it manually only with your own layout without `SiteProviders`. Changing the media domain = changing one env
variable; the component follows automatically.
> NIE hardkoduj `<link rel="preconnect" href="https://media.klient.pl">` ręcznie
> w layoutcie — to zaszywa domenę klienta w kodzie. Użyj MediaPreconnect, który
> bierze ją z env.
> Do NOT hard-code `<link rel="preconnect" href="https://media.klient-media.com">` manually
> in the layout — that bakes the client's domain into the code. Use MediaPreconnect, which
> takes it from env.
## `next.config.ts` — obrazy i nagłówki uploadów
## `next.config.ts` — images and upload headers
- `buildImagesConfig({ serverUrl?, production?, publicUrl?, extraHosts? })` → `images` w
`next.config.ts`: `formats` AVIF + WebP, `minimumCacheTTL` 31 dni, `remotePatterns` z
`R2_PUBLIC_URL` (`publicUrl`) i `extraHosts` (https). Poza produkcją (`production`, domyślnie
`NODE_ENV === 'production'`) także media serwowane przez aplikację — `/api/media/file/**` na
`NEXT_PUBLIC_SERVER_URL` (`serverUrl`) — i `dangerouslyAllowLocalIP: true` dla localhost /
sieci prywatnej (Next 16 inaczej je odrzuca). Wynik rozpakuj i nadpisz:
`images: { ...buildImagesConfig(), /* własne */ }`.
- `buildUploadSecurityHeaders({ collections? })` (domyślnie `['media']`) → nagłówki dla
`/api/<slug>/file/:path*`: sandbox CSP + `nosniff` (SVG z uploadu bez skryptów). security.md.
- `buildImagesConfig({ serverUrl?, production?, publicUrl?, extraHosts? })` → `images` in
`next.config.ts`: `formats` AVIF + WebP, `minimumCacheTTL` 31 days, `remotePatterns` from
`R2_PUBLIC_URL` (`publicUrl`) and `extraHosts` (https). Outside production (`production`, default
`NODE_ENV === 'production'`) also media served by the app — `/api/media/file/**` on
`NEXT_PUBLIC_SERVER_URL` (`serverUrl`) — and `dangerouslyAllowLocalIP: true` for localhost /
private networks (Next 16 rejects them otherwise). Spread the result and override:
`images: { ...buildImagesConfig(), /* your own */ }`.
- `buildUploadSecurityHeaders({ collections? })` (default `['media']`) → headers for
`/api/<slug>/file/:path*`: sandbox CSP + `nosniff` (uploaded SVG without scripts). security.md.
## YouTube bez ładowania iframe — `YouTubeEmbed`
## YouTube without loading the iframe — `YouTubeEmbed`
`<YouTubeEmbed videoId title playLabel note? poster? classNames? />` z `@intecion/ipal-kit/client` —
iframe ładuje się dopiero po kliknięciu.
`<YouTubeEmbed videoId title playLabel note? poster? classNames? />` from `@intecion/ipal-kit/client` —
the iframe loads only after a click.
## Wyłącz / nadpisz
## Turn off / override
- `buildR2Storage` — opt-in: bez wpięcia w `plugins` media idą na dysk Payloada; bez `R2_*` też
dysk. Zwraca zwykły plugin `s3Storage` — potrzebujesz innych opcji storage-s3 (np. `prefix`,
`clientUploads`)? Wywołaj `s3Storage` sam zamiast `buildR2Storage`.
- `MediaPreconnect` — w `SiteProviders` domyślnie włączony, wyłączenie: `preconnect={false}`.
- `buildImagesConfig` / `buildUploadSecurityHeaders` — zwracają zwykłe obiekty do rozpakowania i
nadpisania; nic nie jest wpinane automatycznie.
- `buildR2Storage` — opt-in: not wired into `plugins` → media go to Payload's disk; without `R2_*` also
disk. It returns a plain `s3Storage` plugin — need other storage-s3 options (e.g. `prefix`,
`clientUploads`)? Call `s3Storage` yourself instead of `buildR2Storage`.
- `MediaPreconnect` — on by default in `SiteProviders`, turn off with `preconnect={false}`.
- `buildImagesConfig` / `buildUploadSecurityHeaders` — return plain objects to spread and
override; nothing is wired automatically.