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
+320 -202
View File
@@ -1,135 +1,144 @@
# Deployment — zmienne środowiskowe i produkcja
# Deployment — environment variables and production
Jedno źródło prawdy o zmiennych środowiskowych (wszystkie, co znaczą, wymagane
czy nie) oraz jak wdrożyć projekt na produkcję spójnie. Env jest częścią
deploymentu — te same zmienne w dev (.env) i na produkcji (runtime hostingu).
The single source of truth about environment variables (all of them, what they mean,
required or not) and how to deploy a project to production consistently. Env is part
of deployment — the same variables in dev (.env) and in production (the Coolify app).
Powiązane: [PROGRAMISTA.md](./dev/PROGRAMISTA.md) (od zera do działającej strony, §4 wdrożenie),
[env.md](./env.md) (walidacja na starcie), [storage.md](./storage.md) (R2), [email.md](./email.md) (Graph),
[security.md](./security.md), [integrations.md](./integrations.md) (status integracji w panelu).
**Every project is deployed with Coolify (v4)** on servers the team runs; the team also runs the DNS
zones. This page describes that one path (§4); other hosts — a short note at the end of §4.
Coolify labels below may differ slightly between Coolify versions.
Related: [PROGRAMISTA.md](./dev/PROGRAMISTA.md) (from zero to a working site, §4 deployment),
[env.md](./env.md) (validation at startup), [storage.md](./storage.md) (R2), [email.md](./email.md) (Graph),
[security.md](./security.md), [integrations.md](./integrations.md) (integration status in the panel).
---
## 1. ZMIENNE ŚRODOWISKOWE — pełna lista
## 1. ENVIRONMENT VARIABLES — full list
### Rdzeń (WYMAGANE — projekt bez nich nie wstanie)
### Core (REQUIRED — the project will not start without them)
```bash
# Baza danych (Mongo albo Postgres — zależnie od projektu)
DATABASE_URI=mongodb://... # albo postgres://... / file:./dev.db (dev)
# Database (Mongo or Postgres — depending on the project)
DATABASE_URI=mongodb://... # or postgres://... / file:./dev.db (dev)
# Sekret Payload (podpisywanie sesji/tokenów) — losowy, długi
PAYLOAD_SECRET=<losowy-ciąg-min-32-znaki>
# Payload secret (signs sessions/tokens) — random, long
PAYLOAD_SECRET=<random-string-min-32-chars>
# Publiczny URL serwisu (canonical, hreflang, OG, manifest)
# Public site URL (canonical, hreflang, OG, manifest)
NEXT_PUBLIC_SERVER_URL=https://klient.pl # dev: http://localhost:3000
```
### Email — Graph (OPCJONALNE, agencyjne, gdy transport = Graph)
### Email — Graph (OPTIONAL, agency-level, when transport = Graph)
```bash
GRAPH_TENANT_ID=<azure-tenant-id>
GRAPH_CLIENT_ID=<azure-app-client-id>
GRAPH_CLIENT_SECRET=<azure-app-secret>
GRAPH_SENDER=[email protected] # wspólna skrzynka
GRAPH_SENDER=[email protected] # shared mailbox
```
Potrzebne wszystkie 4. Gdy w panelu wybrano Graph, a któregoś brak — `mailAdapter()` wysyła przez
SMTP z panelu i zgłasza to w Site Integrations (status `graph-unavailable`). Patrz email.md.
All 4 are needed. When Graph is selected in the panel and one is missing — `mailAdapter()` sends through
the SMTP from the panel and reports it in Site Integrations (status `graph-unavailable`). See email.md.
### Storage — R2 (OPCJONALNE w dev, na produkcji zalecane)
### Storage — R2 (OPTIONAL in dev, recommended in production)
```bash
R2_BUCKET=<nazwa-bucketa>
R2_BUCKET=<bucket-name>
R2_ENDPOINT=https://<ACCOUNT_ID>.r2.cloudflarestorage.com
R2_ACCESS_KEY_ID=<access-key>
R2_SECRET_ACCESS_KEY=<secret-key>
R2_PUBLIC_URL=https://media.klient.pl # custom domena (obrazy publiczne)
R2_PUBLIC_URL= # usually EMPTY: media served through the app (§6, storage.md)
# or https://media.klient-media.com (custom domain, zone on Cloudflare)
```
Komplet 4 kluczy → R2. Brak → lokalny dysk (częściowy zestaw → ostrzeżenie w logu + dysk).
Poza produkcją samo `R2_PUBLIC_URL` → media tylko do odczytu. Patrz storage.md.
All 4 keys → R2. None → local disk (a partial set → warning in the log + disk).
`R2_PUBLIC_URL` empty → files in R2, served by the app at `/api/media/file/<name>`; set →
URLs point at that domain. Outside production, `R2_PUBLIC_URL` alone → read-only media. See storage.md.
### Tabela — wszystkie zmienne czytane przez plugin
### Table — all variables read by the plugin
| Zmienna | Wymagana | Warstwa | Opis |
| Variable | Required | Layer | Description |
|---|---|---|---|
| `DATABASE_URI` | ✅ | infra | połączenie z bazą (czyta je config projektu, nie plugin) |
| `PAYLOAD_SECRET` | ✅ | infra | sekret Payload (j.w.) |
| `NEXT_PUBLIC_SERVER_URL` | ✅ | infra | publiczny URL (canonical, OG, sitemap, IndexNow) |
| `NODE_ENV` | ⬜ | infra | `production` zaostrza `ipalEnvRules` (R2, `IPAL_IP_HEADER`) i wyłącza tryb read-only mediów |
| `DATABASE_URI` | ✅ | infra | database connection (read by the project config, not the plugin) |
| `PAYLOAD_SECRET` | ✅ | infra | Payload secret (as above) |
| `NEXT_PUBLIC_SERVER_URL` | ✅ | infra | public URL (canonical, OG, sitemap, IndexNow) |
| `NODE_ENV` | ⬜ | infra | `production` tightens `ipalEnvRules` (R2, `IPAL_IP_HEADER`) and turns off read-only media mode |
| `GRAPH_TENANT_ID` | ⬜ | email | Azure tenant (Graph) |
| `GRAPH_CLIENT_ID` | ⬜ | email | Azure app id |
| `GRAPH_CLIENT_SECRET` | ⬜ | email | Azure secret |
| `GRAPH_SENDER` | ⬜ | email | skrzynka nadawcza |
| `R2_BUCKET` | ⬜ (✅ prod) | storage | bucket R2 |
| `R2_ENDPOINT` | ⬜ (✅ prod) | storage | endpoint S3 R2 |
| `R2_ACCESS_KEY_ID` | ⬜ (✅ prod) | storage | klucz R2 |
| `R2_SECRET_ACCESS_KEY` | ⬜ (✅ prod) | storage | sekret R2 |
| `R2_PUBLIC_URL` | ⬜ (✅ prod) | storage | custom domena mediów (dev: także ścieżka `/media`) |
| `IPAL_IP_HEADER` | ⬜ (✅ prod) | formularze | nagłówek z prawdziwym IP dla rate limitu (`cf-connecting-ip`, `x-forwarded-for`); bez niego ostrzeżenie w logu |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | formularze | fallback, gdy kluczy Turnstile nie ma w Site Integrations |
| `INDEXNOW_KEY` | ⬜ | SEO | klucz IndexNow (ma pierwszeństwo przed kluczem z panelu) |
| `IPAL_NOINDEX` | ⬜ | SEO | `1`/`true`/`yes` **tylko na stagingu** — cała strona noindex (robots, meta, `X-Robots-Tag`) |
| `GRAPH_SENDER` | ⬜ | email | sender mailbox |
| `R2_BUCKET` | ⬜ (✅ prod) | storage | R2 bucket |
| `R2_ENDPOINT` | ⬜ (✅ prod) | storage | R2 S3 endpoint |
| `R2_ACCESS_KEY_ID` | ⬜ (✅ prod) | storage | R2 key |
| `R2_SECRET_ACCESS_KEY` | ⬜ (✅ prod) | storage | R2 secret |
| `R2_PUBLIC_URL` | ⬜ (✅ prod in `ipalEnvRules`) | storage | media domain attached to the bucket; empty = media through the app (§6 — then relax the rule, env.md); dev: also the `/media` path |
| `IPAL_IP_HEADER` | ⬜ (✅ prod) | forms | header with the real IP for the rate limit (`cf-connecting-ip`, `x-forwarded-for`); without it, a warning in the log |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | forms | fallback when the Turnstile keys are not in Site Integrations |
| `INDEXNOW_KEY` | ⬜ | SEO | IndexNow key (takes precedence over the key from the panel) |
| `IPAL_NOINDEX` | ⬜ | SEO | `1`/`true`/`yes` **on staging only** — the whole site is noindex (robots, meta, `X-Robots-Tag`) |
„✅ prod” = wymagane przez `ipalEnvRules({ storage: true })` / `({ ipHeader: true })` przy
`NODE_ENV=production` — o ile projekt wywołuje walidację (env.md). Sam plugin nie przerywa startu
przy braku tych zmiennych.
"✅ prod" = required by `ipalEnvRules({ storage: true })` / `({ ipHeader: true })` with
`NODE_ENV=production` — as long as the project runs the validation (env.md). The plugin itself does not stop
startup when these variables are missing.
**Zasada:** wszystkie sekrety to zmienne agencyjne/infrastrukturalne — w `.env`
(dev) i runtime hostingu (prod), NIGDY w repo. Dane per-projekt edytowalne przez
redaktora idą do PANELU (Site Settings, Site Integrations), nie do env.
**Rule:** all secrets are agency/infrastructure variables — in `.env`
(dev) and the Coolify app's Environment Variables (prod, §4.2), NEVER in the repo. Per-project data editable by the
editor goes to the PANEL (Site Settings, Site Integrations), not to env.
### .env.example — zawsze w repo
### .env.example — always in the repo
Każdy projekt ma `.env.example` z listą zmiennych (bez wartości/sekretów) —
szablon dla następnej osoby. Commituj go; `.env` (z wartościami) NIGDY.
Every project has a `.env.example` listing the variables (no values/secrets) —
a template for the next person. Commit it; never commit `.env` (with values).
---
## 2. PRZED DEPLOYEM — checklist
## 2. BEFORE DEPLOY — checklist
- [ ] `pnpm build` (skrypt z `--webpack`, §3) przechodzi LOKALNIE (nie tylko dev)
- [ ] Wszystkie wymagane env ustawione na hostingu (runtime)
- [ ] `NEXT_PUBLIC_SERVER_URL` = produkcyjny URL (nie localhost)
- [ ] `PAYLOAD_SECRET` inny niż w dev (produkcyjny sekret)
- [ ] Baza produkcyjna (nie dev/SQLite)
- [ ] HSTS włączony (buildSecurityHeaders hsts: production)
- [ ] Media: R2 z custom domeną (jeśli używane) — obrazy publiczne
- [ ] Migracja mediów lokalne→R2 (jeśli przełączasz)
- [ ] Strony polityk + baner cookies ([PROGRAMISTA.md §5](./dev/PROGRAMISTA.md))
- [ ] `IPAL_NOINDEX` NIE ustawione na produkcji
- [ ] `pnpm build` (script with `--webpack`, §3) passes LOCALLY (not only dev)
- [ ] All required env set in the Coolify app, with the right build/runtime availability (§4.2)
- [ ] `NEXT_PUBLIC_SERVER_URL` = production URL (not localhost), the same host as the Coolify domain you redirect to (§4.1)
- [ ] `PAYLOAD_SECRET` different from dev (production secret)
- [ ] Production database (not dev/SQLite); Postgres: migrations run on container start (§4.3)
- [ ] Health check on `/api/health` set in Coolify (§4.4)
- [ ] Scheduled database backups to S3/R2 on (§4.6)
- [ ] HSTS on (buildSecurityHeaders hsts: production)
- [ ] Media: R2 (served through the app, or a media domain on Cloudflare — §6), or a persistent volume (§4.8)
- [ ] Media migration local→R2 (if you switch)
- [ ] Policy pages + cookie banner ([PROGRAMISTA.md §5](./dev/PROGRAMISTA.md))
- [ ] `IPAL_NOINDEX` NOT set in production
---
## 3. BUDOWANIE NA PRODUKCJĘ
## 3. BUILDING FOR PRODUCTION
### Build script (Next 16 + Payload)
```json
// package.json — --webpack KONIECZNE (Turbopack konfliktuje z withPayload)
// package.json — --webpack REQUIRED (Turbopack conflicts with withPayload)
"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"
```
`--max-old-space-size` — Payload + Next bywają pamięciożerne przy buildzie;
3072 MB zapobiega OOM na mniejszych maszynach.
`--max-old-space-size` — Payload + Next can be memory-hungry during the build;
3072 MB prevents OOM on smaller machines.
### Kolejność build → migracje → start
### Order: build → migrations → start
What Coolify runs (install/build/start commands in the app's build settings):
```bash
pnpm install --frozen-lockfile # dokładnie z lockfile (powtarzalny build)
pnpm generate:types # typy z kolekcji
pnpm install --frozen-lockfile # exactly from the lockfile (repeatable build)
pnpm generate:types # types from collections
pnpm build # --webpack
# migracje bazy (jeśli Postgres z migracjami):
pnpm payload migrate
pnpm start # produkcyjny serwer
# Postgres: pending migrations run when the NEW container starts, before it is healthy (§4.3)
pnpm start # production server, port 3000
```
---
## 3a. Pułapka: metadata w <body> zamiast <head> (htmlLimitedBots)
## 3a. Pitfall: metadata in <body> instead of <head> (htmlLimitedBots)
Next 16 streamuje metadata dynamicznych stron do `<body>` (przenosi do head
skryptem JS). Crawlery bez JS widzą canonical/hreflang/title/favicon poza head →
utrata SEO. **Każdy projekt** tego potrzebuje w next.config:
Next 16 streams metadata of dynamic pages into `<body>` (moves it to head with a
JS script). Crawlers without JS see canonical/hreflang/title/favicon outside head →
SEO loss. **Every project** needs this in next.config:
```ts
const nextConfig: NextConfig = {
@@ -139,115 +148,171 @@ const nextConfig: NextConfig = {
}
```
Weryfikacja: `curl -A "Googlebot" URL | grep canonical` — musi być w `<head>`.
Szczegóły i objawy: seo.md (sekcja htmlLimitedBots).
Check: `curl -A "Googlebot" URL | grep canonical` — it must be in `<head>`.
Details and symptoms: seo.md (htmlLimitedBots section).
## 3a2. ISR — cache stron (metadata w head + szybkość)
## 3a2. ISR — page cache (metadata in head + speed)
Dla stron contentowych (page.tsx) użyj ISR: `export const revalidate = 3600`.
Cache'uje całą stronę z gotowym `<head>` → metadata zawsze w head (nie body,
brak race condition streamingu), TTFB ~20ms, brak 503 (cold start).
For content pages (page.tsx) use ISR: `export const revalidate = 3600`.
It caches the whole page with a finished `<head>` → metadata always in head (not body,
no streaming race condition), TTFB ~20ms, no 503 (cold start).
```ts
// app/(frontend)/[locale]/[[...slug]]/page.tsx
export const revalidate = 3600 // 1h; albo krócej, albo on-demand
export const revalidate = 3600 // 1h; or shorter, or on-demand
```
UWAGA: ISR i `force-dynamic` się WYKLUCZAJĄ. Strony → ISR (revalidate).
sitemap/robots → force-dynamic (bo generują przy żądaniu). Nie mieszaj na jednej
trasie. Treść z panelu: ISR = redaktor czeka do rewalidacji; rozważ on-demand
revalidation (`buildRevalidateHook` na kolekcjach; globale — własny afterChange z
`revalidatePath('/', 'layout')`, plugin ich nie rewaliduje). Patrz [seo.md](./seo.md), [hooks.md](./hooks.md).
NOTE: ISR and `force-dynamic` are MUTUALLY EXCLUSIVE. Pages → ISR (revalidate).
sitemap/robots → force-dynamic (they generate on request). Do not mix them on one
route. Content from the panel: ISR = the editor waits for revalidation; consider on-demand
revalidation (`buildRevalidateHook` on collections; globals — your own afterChange with
`revalidatePath('/', 'layout')`, the plugin does not revalidate them). See [seo.md](./seo.md), [hooks.md](./hooks.md).
## 3a3. SSG a dostęp do bazy przy buildzie (WAŻNE dla SEO)
## 3a3. SSG and database access at build time (IMPORTANT for SEO)
`generateStaticParams` (z lib/content) prerenderuje strony jako SSG — head
synchroniczny, SEO 100/100. ALE żeby prerenderować, **build musi mieć dostęp do
bazy** (generateStaticParams czyta strony z bazy w czasie buildu).
`generateStaticParams` (from lib/content) prerenders pages as SSG — synchronous
head, SEO 100/100. BUT to prerender, **the build must have access to the
database** (generateStaticParams reads pages from the database at build time).
- **Build MA dostęp do bazy** (baza w tej samej sieci Docker, dostępna w build
stage) → strony prerenderowane jako SSG (`●`), head synchroniczny → SEO OK ✓
- **Build NIE MA dostępu** (izolowany build stage) → generateStaticParams zwraca
`[]` (plugin łapie błąd, build nie pada), ale strony renderują się on-demand
(dynamicznie) → head może streamować do body → problem SEO wraca ✗
- **Build HAS database access** (database reachable from the Coolify build, e.g. on the same
server/network) → pages prerendered as SSG (`●`), synchronous head → SEO OK ✓
- **Build has NO access** (isolated build stage) → generateStaticParams returns
`[]` (the plugin catches the error, the build does not fail), but pages render on-demand
(dynamically) → head may stream into body → the SEO problem is back ✗
`generateStaticParams` obejmuje tylko kolekcję stron (max 1000 dokumentów na język) — wpisy
kolekcji treści renderują się on-demand (ISR).
`generateStaticParams` covers only the pages collection (max 1000 documents per language) — entries
of content collections render on-demand (ISR).
Plugin zabezpiecza build przed CRASHEM (try/catch → `[]`), ale to NIE zastępuje
dostępu do bazy. **Dla pełnego SSG/SEO zapewnij, że build kontenerowy widzi bazę.**
The plugin protects the build from a CRASH (try/catch → `[]`), but that does NOT replace
database access. **For full SSG/SEO, make sure the container build can reach the database.**
W Coolify/Docker: baza (Mongo/Postgres) powinna być dostępna podczas `pnpm build`,
nie tylko w runtime. Jeśli build jest w izolowanej sieci — rozważ:
- uruchom bazę w tej samej sieci Docker co build stage, albo
- build z DATABASE_URI wskazującym na dostępną bazę (nie wewnętrzny host niedostępny w buildzie).
In Coolify: the database (Mongo/Postgres) should be reachable during `pnpm build`,
not only at runtime — `DATABASE_URI` (and `PAYLOAD_SECRET`) need **Build time** availability (§4.2) and a
host the build can reach. If the build cannot reach the database's internal host:
- put the database resource on the same server/network as the app, or
- build with a `DATABASE_URI` pointing to an address reachable from the build.
Weryfikacja: po buildzie `pnpm build` pokazuje trasy jako `●` (SSG), nie `ƒ`
(Dynamic). Jeśli `ƒ` mimo generateStaticParams → build nie miał dostępu do bazy.
Check: after the build, `pnpm build` shows routes as `●` (SSG), not `ƒ`
(Dynamic). If `ƒ` despite generateStaticParams → the build had no database access.
## 3b. Pułapka: prerender tras zależnych od bazy (KONIECZNE)
## 3b. Pitfall: prerendering database-dependent routes (REQUIRED)
Next domyślnie **prerenderuje** trasy typu `sitemap.ts` w czasie `next build` —
traktuje je jako statyczne. Jeśli taka trasa czyta bazę (sitemap → Payload →
Mongo/Postgres), build **próbuje połączyć się z bazą**. A kontener budujący
(Coolify/Docker/Railway/CI) zwykle NIE ma dostępu do sieci bazy → połączenie
pada (`ENOTFOUND`, `MongooseServerSelectionError`) → **build się wywala**.
By default Next **prerenders** routes like `sitemap.ts` during `next build` —
it treats them as static. If such a route reads the database (sitemap → Payload →
Mongo/Postgres), the build **tries to connect to the database**. And the build container
(Coolify build, CI) often has NO access to the database network → the connection
fails (`ENOTFOUND`, `MongooseServerSelectionError`) → **the build crashes**.
**Rozwiązanie — `force-dynamic` na trasach zależnych od bazy:**
**Fix — `force-dynamic` on database-dependent routes:**
```ts
// app/sitemap.ts
export { sitemap as default } from '@/lib/content'
export const dynamic = 'force-dynamic' // generuj w runtime, nie w buildzie
export const dynamic = 'force-dynamic' // generate at runtime, not at build time
```
To mówi Next: nie prerenderuj w buildzie, generuj w runtime (gdy baza jest
dostępna). Dotyczy KAŻDEJ trasy czytającej bazę podczas renderowania:
This tells Next: do not prerender at build time, generate at runtime (when the database is
reachable). It applies to EVERY route that reads the database while rendering:
- `app/sitemap.ts` → `force-dynamic`
- inne trasy/strony czytające bazę w prerenderze → rozważ `force-dynamic` albo
obsłuż błąd bazy (try/catch z fallbackiem)
- other routes/pages reading the database during prerender → consider `force-dynamic` or
handle the database error (try/catch with a fallback)
Plugin dodatkowo zabezpiecza handler sitemap (łapie błąd bazy, zwraca pustą
mapę), więc build nie padnie nawet bez `force-dynamic` — ale to siatka
bezpieczeństwa, nie właściwe rozwiązanie. Zawsze dodawaj `force-dynamic`.
The plugin also guards the sitemap handler (catches the database error, returns an empty
map), so the build will not fail even without `force-dynamic` — but that is a safety
net, not the proper fix. Always add `force-dynamic`.
**Strona 404** (`not-found.tsx`) czytająca ustawienia z bazy — ten sam problem.
Opakuj `getCachedPayload()` w try/catch, żeby brak bazy w buildzie nie wywalił
prerenderu 404 (fallback na statyczne teksty).
**404 page** (`not-found.tsx`) reading settings from the database — the same problem.
Wrap `getCachedPayload()` in try/catch so a missing database at build time does not crash
the 404 prerender (fallback to static texts).
**Weryfikacja lokalna** (symuluj brak bazy):
**Local check** (simulate a missing database):
```bash
DATABASE_URI=mongodb://invalid-host:27017/test pnpm build
# build musi przejść (kod 0), mimo niedostępnej bazy
# the build must pass (exit code 0) despite the unreachable database
```
## 4. HOSTING (Coolify / Docker)
## 4. HOSTING — Coolify
### Zmienne runtime, nie build
One Coolify **application** per project (built from the Git repo) plus a Coolify **database** resource
(Postgres or Mongo) on the same server. Order of the steps below = order of setting up a new project.
Zmienne środowiskowe ustaw w **runtime** hostingu (Coolify → Environment
Variables), nie zapiekaj w build. `NEXT_PUBLIC_*` są wyjątkiem — wchodzą w build
(bo publiczne, w bundlu klienta), więc muszą być dostępne PODCZAS buildu.
### 4.1 Application and domains
### Persystencja mediów
- **Port** 3000 (`pnpm start`). Do not publish a host port mapping — it disables rolling updates (§4.4).
- **Domains**: both addresses, e.g. `https://klient.pl,https://www.klient.pl`. Coolify's proxy issues a
Let's Encrypt certificate per domain (HTTP challenge — DNS must already point at the server, §6 rows 1–3).
- **Redirect** www ↔ apex in the app's domain/redirect setting (Direction) so the canonical host is the one in
`NEXT_PUBLIC_SERVER_URL` — canonical, hreflang and sitemap URLs use that variable, the redirect must agree with it.
Jeśli media lokalne (nie R2) — potrzebują **wolumenu** (inaczej znikną przy
redeployu). Dlatego R2 jest zalecane na produkcji: media poza kontenerem,
przetrwają redeploy. Patrz storage.md.
### 4.2 Environment variables — where and when
### Health check
Coolify → the application → **Environment Variables**. Each variable can be available at **build time**,
at **runtime**, or both (newer versions: two switches *Build time* / *Runtime*; older: a *Build Variable*
checkbox; default: both). A changed variable takes effect only after a **redeploy** (build-time ones need a rebuild).
Zalecane: endpoint z pluginu — robi realny round-trip do bazy (`find` z `limit: 1`, `depth: 0`)
i zwraca 200/503, więc Coolify/Docker odróżni „proces żyje” od „app gotowa, baza dostępna”.
Zwykle wystarczy re-eksport z `lib/content` (PROGRAMISTA.md §2.8) — `healthRoute` to
`createHealthRoute` pingujący kolekcję stron z `createContentHelpers`:
| Variables | Build time | Runtime | Why |
|---|---|---|---|
| `NEXT_PUBLIC_SERVER_URL`, `NEXT_PUBLIC_TURNSTILE_SITE_KEY` (all `NEXT_PUBLIC_*`) | ✅ | ✅ | `next build` inlines them into the client bundle — missing at build = missing in the browser |
| `DATABASE_URI`, `PAYLOAD_SECRET` | ✅ only if the build prerenders from the database (§3a3), otherwise ⬜ | ✅ | SSG (`generateStaticParams`) needs the database during `pnpm build`; DB-reading routes stay `force-dynamic` either way (§3b) |
| `R2_*`, `GRAPH_*`, `TURNSTILE_SECRET_KEY`, `INDEXNOW_KEY`, `IPAL_IP_HEADER` | ⬜ | ✅ | read at runtime only — keep secrets out of the build |
| `NODE_ENV` | — | — | do not set by hand: `next build` / `next start` use `production` |
| `IPAL_NOINDEX` | — | ✅ staging only | never on production |
Multiline values (keys) → mark *Multiline*; values containing `$` → mark *Literal* (otherwise Coolify interpolates
them). Coolify adds its own variables (`COOLIFY_FQDN`, `COOLIFY_URL`, `SOURCE_COMMIT`, `PORT`, `HOST`) — do not use
them instead of `NEXT_PUBLIC_SERVER_URL`. `.env.example` in the repo is the checklist of what to fill in.
### 4.3 Database migrations (Postgres)
Mongo needs no migrations — skip this section. Postgres: production never uses `push`; schema changes ship as
committed migrations (`pnpm payload migrate:create` locally).
**Not in Coolify's Pre-/Post-deployment commands:**
- *Pre-deployment* runs in the **old** (still running) container — old code, old migrations — and is **skipped on the
first deployment**;
- *Post-deployment* runs after Coolify has already switched traffic to the new container, and its failure is only logged.
**Run them when the new container starts, before it reports healthy** — one of:
```ts
// payload.config.ts — preferred: Payload runs pending migrations on init when NODE_ENV=production
import { migrations } from './migrations'
db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URI }, prodMigrations: migrations }),
```
```bash
# or the start command (needs the Payload CLI and sources in the image):
pnpm payload migrate && pnpm start
```
With the health check (§4.4) the new container gets traffic only after the migrations succeeded and the database
answers; a failed migration leaves the old container serving. Note: `prodMigrations` runs on every Payload init
with `NODE_ENV=production` — also during `next build` when the build reaches the database (§3a3).
**Backward-compatible migrations only.** During a rolling update the old container still serves on the migrated
schema: add columns/tables first, drop or rename in a later release (`ipal-migrate-fields` skill). Take a
**Backup now** (§4.6) before a large migration.
### 4.4 Health check and rolling updates
Coolify → the application → **Health Checks**: HTTP, path `/api/health`, port 3000, a start period long enough
for migrations. Coolify starts the new container while the old one keeps serving, waits until it is healthy, then
switches; an unhealthy new container is removed and **the old one stays**. Without a health check any started
container counts as ready. Rolling updates are off when the app publishes a host port, has a custom/fixed container
name, or a custom IP — avoid those.
The endpoint comes from the plugin — it does a real round-trip to the database (`find` with `limit: 1`, `depth: 0`)
and returns 200/503, so Coolify can tell "process alive" from "app ready, database reachable".
Usually a re-export from `lib/content` is enough (PROGRAMISTA.md §2.8) — `healthRoute` is
`createHealthRoute` pinging the pages collection from `createContentHelpers`:
```ts
// app/api/health/route.ts
export { healthRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic' // nigdy nie prerenderuj/cache'uj health
export const dynamic = 'force-dynamic' // never prerender/cache health
```
Własne ustawienia — `createHealthRoute` wprost:
Custom settings — `createHealthRoute` directly:
```ts
import { createHealthRoute } from '@intecion/ipal-kit'
@@ -256,91 +321,144 @@ export const dynamic = 'force-dynamic'
export const GET = createHealthRoute({ getCachedPayload, collection: 'pages' })
```
| Opcja | Domyślnie | Opis |
| Option | Default | Description |
|---|---|---|
| `getCachedPayload` | — (wymagane) | ten sam akcesor co w reszcie aplikacji |
| `collection` | `'pages'` | kolekcja pingowana round-tripem — musi istnieć |
| `extra` | — | `async () => ({ … })` — dodatkowe sprawdzenia, wynik doklejany do body (po polach bazowych — te same klucze je nadpisują); wyjątek → 503 |
| `getCachedPayload` | — (required) | the same accessor as in the rest of the app |
| `collection` | `'pages'` | collection pinged by the round-trip — must exist |
| `extra` | — | `async () => ({ … })` — extra checks, the result is appended to the body (after the base fields — the same keys override them); an exception → 503 |
Odpowiedź (`content-type: application/json`, `cache-control: no-store`):
Response (`content-type: application/json`, `cache-control: no-store`):
- 200: `{ status: 'ok', db: 'up', timestamp, tookMs, …extra }`
- 503: `{ status: 'error', db: 'down', timestamp, tookMs }` — bez treści błędu (ta idzie do logu
serwera: `[ipal] createHealthRoute: database unreachable`). Wyjątek z `extra` też daje `db: 'down'`.
- 503: `{ status: 'error', db: 'down', timestamp, tookMs }` — no error details (they go to the
server log: `[ipal] createHealthRoute: database unreachable`). An exception from `extra` also gives `db: 'down'`.
Ustaw health check Coolify na `/api/health`. Alternatywnie (prościej, bez bazy): ping strony
głównej. Jeśli baza wstaje wolniej niż app, daj odpowiedni start period — inaczej orchestrator
ubije kontener w oknie startu.
**Turn off / override:** the route is opt-in — without the file `app/api/health/route.ts` nothing is created;
you can also write your own route from scratch (or point the health check at the home page — no database check).
**Wyłącz / nadpisz:** trasa jest opt-in — bez pliku `app/api/health/route.ts` nic nie powstaje;
można też napisać własną trasę od zera.
### 4.5 Rollback
### Integracje w panelu
Coolify → the application → **Rollback** → *Available images* → roll back to an earlier image. Only images kept by
the image retention setting (*Images to keep*) are available — keep a few. A rollback swaps the code only: it does
**not** undo database migrations, volumes or external services. If a migration has to be undone → restore the backup
taken before the deploy (§4.6), then roll back the image.
Błędy maila (SMTP/Graph) i Turnstile widać po deployu w panelu: alert na dashboardzie i baner na
zakładce Site Integrations — patrz [integrations.md](./integrations.md).
### 4.6 Database backups
- Coolify → **S3 Storages**: add the backup target (any S3-compatible, e.g. a Cloudflare R2 bucket for backups —
not the media bucket) and validate the connection.
- The database resource → **Backups**: a schedule (daily or cron), *Enable S3*, retention for local and S3 copies
(count / days / size); raise the timeout for large databases. Postgres backups are `pg_dump` custom-format files.
- **Backup now** before every risky operation: a seed that updates content, a large migration, a field migration.
- **Restore**: the database resource → **Import Backup** (upload a file, a server path, or a file from S3) → check the
generated restore command → start and watch the restore output. Stop writes from the app first. Manual
alternative: `pg_restore --clean --if-exists --no-owner -d "$DATABASE_URI" backup.dump`.
- **Test restores** periodically into a throw-away database — an untested backup is not a backup.
Mongo resources have the same Backups / Import Backup screens (`mongodump` archives).
### 4.7 Running a command in production (seed, one-off scripts)
Coolify → the application → **Terminal** → pick the app container (or on the server:
`docker exec -it <container> sh`). The container has the runtime env, so scripts reach the production database.
For a seed (script, flags and data format: [seeding.md](./seeding.md)):
1. **dry run** — `SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts`, read the planned changes;
2. **Backup now** on the database (§4.6);
3. the real run; check the panel and the site.
The seed script and its dependencies must be in the image (they are when Coolify builds from the whole repo).
### 4.8 Media persistence
With R2 (recommended) media live outside the container and survive redeploys and rollbacks. Without R2 media are on
the container disk → add a Coolify **Persistent Storage** volume for the upload directory (the upload collection's
`staticDir` — by default a folder named after the slug, e.g. `media`; check the absolute path inside the container), otherwise every redeploy deletes them. See storage.md.
### Integrations in the panel
Mail (SMTP/Graph) and Turnstile errors are visible in the panel after deploy: an alert on the dashboard and a banner on
the Site Integrations tab — see [integrations.md](./integrations.md).
### Other hosts
Not used for our projects. The plugin is host-agnostic: on any Node host keep the same rules — `NEXT_PUBLIC_*`
at build time, secrets at runtime, migrations before the new version takes traffic, a health check on `/api/health`,
media in R2 or on a persistent disk.
---
## 5. PO DEPLOYU — weryfikacja
## 5. AFTER DEPLOY — checks
- [ ] Strona główna `/` przekierowuje na locale (`/pl`)
- [ ] Panel `/admin` działa, logowanie OK
- [ ] Formularz wysyła (test przez panel: Send test)
- [ ] Media się wyświetlają (jeśli R2 — custom domena działa, nie 403)
- [ ] Favicon w `<head>` (patrz seo.md — Google cache'uje wolno)
- [ ] HTTPS + nagłówki bezpieczeństwa (sprawdź np. securityheaders.com)
- [ ] Sitemap `/sitemap.xml` i `/robots.txt` odpowiadają
- [ ] Rekordy DNS z §6 dodane i sprawdzone `dig`
- [ ] Home page `/` redirects to a locale (`/pl`)
- [ ] Panel `/admin` works, login OK
- [ ] The form sends (test from the panel: Send test)
- [ ] Media display — through the app: `curl -sI https://klient.pl/api/media/file/<file>` → 200; media domain: no 403
- [ ] Coolify: health check green, a scheduled backup exists (§4.4, §4.6)
- [ ] Favicon in `<head>` (see seo.md — Google caches it slowly)
- [ ] HTTPS + security headers (check e.g. securityheaders.com)
- [ ] Sitemap `/sitemap.xml` and `/robots.txt` respond
- [ ] DNS records from §6 added and checked with `dig`
---
## 6. DNS — rekordy do dodania w strefie
## 6. DNS — records to add to the zone
Strefy DNS projektów prowadzi nasz zespół (nasze serwery albo serwery, którymi
zarządzamy). **Plugin niczego w DNS nie automatyzuje** — poniższe rekordy dodaje
człowiek w strefie domeny klienta. Agent przygotowuje listę z wartościami i
sprawdza `dig` po propagacji. Sprawdzaj na autorytatywnym serwerze strefy
(`dig @<ns> …`) i na publicznym resolverze (`@1.1.1.1`), żeby wykluczyć cache.
Our team runs the projects' DNS zones (our servers or servers we
manage). **The plugin automates nothing in DNS** — a human adds the records below
in the client's domain zone. The agent prepares the list with the values and
checks with `dig` after propagation. Check on the zone's authoritative server
(`dig @<ns> …`) and on a public resolver (`@1.1.1.1`) to rule out caching.
| # | Po co | Rekord | Wartość | Sprawdzenie |
| # | Purpose | Record | Value | Check |
|---|---|---|---|---|
| 1 | Strona (domena główna) | `A` / `AAAA` dla `klient.pl` (albo `ALIAS`/`ANAME`) | IP hostingu | `dig +short klient.pl A` → IP serwera |
| 2 | `www` | `CNAME www` → `klient.pl` (albo `A`) | — | `dig +short www.klient.pl` → ten sam host; `curl -sI https://www.klient.pl` → 301/308 na adres z `NEXT_PUBLIC_SERVER_URL` |
| 3 | Certyfikat TLS (tylko gdy strefa ma CAA) | `CAA klient.pl` | `0 issue "letsencrypt.org"` (lub CA hostingu) | `dig +short klient.pl CAA` — brak rekordów CAA = każdy CA może wystawić |
| 4 | **Google Search Console** — weryfikacja domeny | `TXT` na `klient.pl` (apex) | `google-site-verification=<kod z GSC>` (usługa typu **Domena**) | `dig +short TXT klient.pl \| grep google-site-verification` → potem GSC → Zweryfikuj |
| 5 | **Bing Webmaster** (jeśli używany) | najprościej **import z Search Console** w Bing (bez DNS); inaczej `CNAME <kod>` → `verify.bing.com` | kod z Bing | `dig +short CNAME <kod>.klient.pl` → `verify.bing.com.` |
| 6 | E-mail — **SPF** domeny nadawcy | `TXT` na domenie adresu From | `v=spf1 include:<dostawca> -all` (Microsoft 365: `include:spf.protection.outlook.com`) — **jeden** rekord SPF na domenę, dopisz include do istniejącego | `dig +short TXT <domena> \| grep v=spf1` → dokładnie jeden wynik |
| 7 | E-mail — **DKIM** | wg dostawcy: `CNAME selector1._domainkey` / `selector2._domainkey` (Microsoft 365) albo `TXT <selektor>._domainkey` z kluczem | wartości z panelu dostawcy poczty | `dig +short CNAME selector1._domainkey.<domena>` (lub `TXT`) → wartość dostawcy; potem włącz DKIM u dostawcy |
| 8 | E-mail — **DMARC** | `TXT _dmarc.<domena>` | start: `v=DMARC1; p=none; rua=mailto:dmarc@<domena>`, po sprawdzeniu raportów → `p=quarantine` | `dig +short TXT _dmarc.<domena>` |
| 9 | Media w R2 (jeśli `R2_PUBLIC_URL` = własna subdomena, np. `media.klient.pl`) | własna domena R2 ustawiana w Cloudflare (R2 → bucket → Custom Domains) | — | `curl -sI https://media.klient.pl/<plik>` → 200; root `/` może dawać 404 (patrz storage.md) |
| 1 | Site (apex domain) | `A` / `AAAA` for `klient.pl` | IP of the Coolify server running the app | `dig +short klient.pl A` → server IP |
| 2 | `www` | `CNAME www` → `klient.pl` (or `A` → the same IP) | — | `dig +short www.klient.pl` → same IP; `curl -sI https://www.klient.pl` → 301/308 to the host from `NEXT_PUBLIC_SERVER_URL` (Coolify redirect, §4.1) |
| 3 | TLS certificate — Let's Encrypt via Coolify's proxy | `CAA klient.pl` (only when the zone already has CAA records) | `0 issue "letsencrypt.org"`; port 80 on the server reachable from the internet (HTTP challenge) | `dig +short klient.pl CAA` — no CAA records = any CA may issue; `curl -sI https://klient.pl` → valid certificate |
| 4 | **Google Search Console** — domain verification | `TXT` on `klient.pl` (apex) | `google-site-verification=<code from GSC>` (property type **Domain**) | `dig +short TXT klient.pl \| grep google-site-verification` → then GSC → Verify |
| 5 | **Bing Webmaster** (if used) | simplest: **import from Search Console** in Bing (no DNS); otherwise `CNAME <code>` → `verify.bing.com` | code from Bing | `dig +short CNAME <code>.klient.pl` → `verify.bing.com.` |
| 6 | E-mail — sender domain **SPF** | `TXT` on the domain of the From address | `v=spf1 include:<provider> -all` (Microsoft 365: `include:spf.protection.outlook.com`) — **one** SPF record per domain, add the include to the existing one | `dig +short TXT <domain> \| grep v=spf1` → exactly one result |
| 7 | E-mail — **DKIM** | per provider: `CNAME selector1._domainkey` / `selector2._domainkey` (Microsoft 365) or `TXT <selector>._domainkey` with the key | values from the mail provider's panel | `dig +short CNAME selector1._domainkey.<domain>` (or `TXT`) → provider's value; then turn on DKIM at the provider |
| 8 | E-mail — **DMARC** | `TXT _dmarc.<domain>` | start: `v=DMARC1; p=none; rua=mailto:dmarc@<domain>`, after checking the reports → `p=quarantine` | `dig +short TXT _dmarc.<domain>` |
| 9 | Media in R2 | **default: none** — `R2_PUBLIC_URL` empty, media served by the app; with a media domain: the R2 Custom Domain in the Cloudflare account that hosts that zone (see below) | — | through the app: `curl -sI https://klient.pl/api/media/file/<file>` → 200; media domain: `curl -sI https://<media-domain>/<file>` → 200 (root `/` may return 404, storage.md) |
**Która domena dostaje SPF/DKIM/DMARC (wiersze 6–8)** — ta z adresu **From** wysyłanych maili:
- transport **SMTP z panelu** → domena z pola *From address* w Site Integrations (zwykle domena
klienta); rekordy daje dostawca tej skrzynki;
- transport **Graph** → From to zawsze `GRAPH_SENDER` (skrzynka agencji, [email.md](./email.md)) —
SPF/DKIM/DMARC ustawia się raz dla domeny agencji, nie per projekt; adres z panelu idzie w Reply-To.
**Which domain gets SPF/DKIM/DMARC (rows 6–8)** — the one in the **From** address of sent mail:
- **SMTP from the panel** transport → the domain from the *From address* field in Site Integrations (usually the client's
domain); the records come from that mailbox's provider;
- **Graph** transport → From is always `GRAPH_SENDER` (agency mailbox, [email.md](./email.md)) —
SPF/DKIM/DMARC are set once for the agency domain, not per project; the address from the panel goes into Reply-To.
Bez SPF+DKIM zgodnych z domeną From (DMARC alignment) maile z formularzy lądują w spamie
albo są odrzucane — przycisk *Send test* w panelu pokaże „wysłano”, a mail i tak nie dojdzie.
Sprawdź nagłówek `Authentication-Results` w odebranym teście: `spf=pass`, `dkim=pass`, `dmarc=pass`.
Without SPF+DKIM aligned with the From domain (DMARC alignment) form mail lands in spam
or is rejected — the *Send test* button in the panel will show "sent", and the mail still will not arrive.
Check the `Authentication-Results` header in the received test: `spf=pass`, `dkim=pass`, `dmarc=pass`.
**Cloudflare R2 (wiersz 9):** własną domenę dla bucketu Cloudflare podpina tylko w strefie
obsługiwanej przez Cloudflare — przy strefie na naszych serwerach trzeba to rozwiązać per projekt
(np. osobna domena mediów w Cloudflare). Adres `*.r2.dev` nadaje się tylko do dev.
**Cloudflare R2 (row 9):** 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 zones are on our own servers, so `media.klient.pl` cannot simply
be attached. Options, in order of preference:
**Bez rekordów DNS:** Turnstile (lista hostnamów ustawiana w panelu Cloudflare przy widżecie, nie w
DNS), IndexNow (plik klucza z aplikacji), llms.txt, MCP, Markdown, sitemap.
1. **Serve media through the app (default)** — leave `R2_PUBLIC_URL` empty. Files are stored in R2, Payload serves
them at `/api/media/file/<name>` on the site's own domain: no DNS record, works on any zone. Cost: media traffic
passes through the app (next/image caches optimized variants); relax the `R2_PUBLIC_URL` rule in
`ipalEnvRules` (env.md). Details: storage.md.
2. **A dedicated media domain on Cloudflare** — a separate domain whose zone is in our Cloudflare account (e.g.
`klient-media.com`), attached as the bucket's Custom Domain → `R2_PUBLIC_URL=https://<that domain>`. CDN and
cache rules included; for media-heavy sites.
3. A reverse proxy/cache on the Coolify server (`media.klient.pl` → the bucket) — possible, more moving parts.
4. `*.r2.dev` — rate-limited, **dev/testing only**, never production.
**Search Console przez DNS, nie meta tag.** Weryfikujemy rekordem TXT (wiersz 4) — obejmuje
wszystkie protokoły i subdomeny. Pola weryfikacji meta tagiem w Site Settings (jeśli wersja
pluginu je ma) są **opcjonalne i normalnie puste**. Nie korzystamy z API Search Console — mapę
`https://klient.pl/sitemap.xml` zgłaszasz raz ręcznie w GSC (i w Bing).
**No DNS records needed:** Turnstile (hostname list set in the Cloudflare panel on the widget, not in
DNS), IndexNow (key file served by the app), llms.txt, MCP, Markdown, sitemap.
**Search Console through DNS, not a meta tag.** We verify with a TXT record (row 4) — it covers
all protocols and subdomains. The meta tag verification fields in Site Settings (if the plugin
version has them) are **optional and normally empty**. We do not use the Search Console API — submit the
sitemap `https://klient.pl/sitemap.xml` once by hand in GSC (and in Bing).
---
## DLACZEGO TO WAŻNE
## WHY THIS MATTERS
- **Jedna lista env** — nikt nie zgaduje, czego brakuje
- **Powtarzalny deploy** — frozen-lockfile, ta sama kolejność, każdy projekt tak samo
- **Sekrety bezpieczne** — env/runtime, nigdy repo
- **Media przetrwają** — R2 albo wolumen, nie znikają przy redeployu
- **One env list** — nobody guesses what is missing
- **Repeatable deploy** — frozen-lockfile, the same order, every project the same way
- **Secrets safe** — env/runtime, never the repo
- **Media survive** — R2 or a volume, they do not disappear on redeploy