613 lines
39 KiB
Markdown
613 lines
39 KiB
Markdown
# Deployment — environment variables and production
|
||
|
||
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).
|
||
|
||
**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) (the mail service, SMTP),
|
||
[security.md](./security.md), [integrations.md](./integrations.md) (integration status in the panel).
|
||
|
||
---
|
||
|
||
## 1. ENVIRONMENT VARIABLES — full list
|
||
|
||
### Core (REQUIRED — the project will not start without them)
|
||
|
||
```bash
|
||
# Database (Mongo or Postgres — depending on the project); name = <domain without dots>_prod / _dev (§4.2a)
|
||
DATABASE_URI=mongodb://user:pass@mongo:27017/intecioncom_prod?authSource=admin # or postgres://user:pass@db:5432/intecioncom_prod
|
||
# dev: …/intecioncom_dev, or file:./dev.db
|
||
|
||
# Payload secret (signs sessions/tokens) — random, long
|
||
PAYLOAD_SECRET=<random-string-min-32-chars> # iaplEnvRules: ≥ 32 characters in production (secretMinLength)
|
||
|
||
# Public site URL (canonical, hreflang, OG, manifest)
|
||
NEXT_PUBLIC_SERVER_URL=https://klient.pl # dev: http://localhost:3000
|
||
```
|
||
|
||
**`PAYLOAD_SECRET` — length and changing it.** `iaplEnvRules` refuses a secret shorter than 32 characters in
|
||
production (`secretMinLength`; `0` turns the check off, outside production nothing is checked). Payload (3.94)
|
||
derives its signing key from it (`sha256(secret)`, first 32 hex characters). Changing it on a live site therefore:
|
||
- **logs everyone out** — every login token (the `payload-token` cookie, JWTs from login / refresh / password reset)
|
||
is signed with it and stops being valid;
|
||
- **asks every user for the 2FA code again** — `@clocklimited/payload-2fa` signs its own 2FA cookie with it; the TOTP
|
||
keys themselves are stored as they are, so the authenticator apps keep working;
|
||
- **breaks stored API keys** (only in collections with `useAPIKey`) — Payload stores them encrypted with the secret
|
||
and finds them by an HMAC of it: they no longer authenticate and cannot be revealed — generate new ones;
|
||
- fails uploads that are in progress (client upload receipts are signed with it).
|
||
IAPL itself derives nothing from it. Change it only with the owner's OK, at a quiet time, and tell the editors
|
||
they will have to log in again.
|
||
|
||
### Email — nothing in env
|
||
|
||
Mail needs **no variable**. A site with no SMTP server in the panel sends through the Intecion mail service
|
||
([email.md](./email.md)); SMTP is typed in the panel. What the deploy needs for the mail service:
|
||
|
||
- **`NEXT_PUBLIC_SERVER_URL` / `serverURL` = the public address the site answers on without a redirect** (the service
|
||
calls the site back at `https://<host>/api/iapl/mail-relay/confirm` and follows no redirect: with a www ↔ apex
|
||
redirect in Coolify, `serverURL` names the side that answers).
|
||
- **That route reachable from the internet** — no basic auth on the Coolify app, no firewall or WAF rule in front of
|
||
`/api/iapl/`; behind Cloudflare leave it uncached and unchallenged.
|
||
- **Outbound HTTPS** to `webservices.intecion.net`.
|
||
- **Launch and a domain move need nobody.** A site built on a development address and then served on its real
|
||
domain (or moved to another one) enrols by itself on its first e-mail; the old address's connection in the
|
||
database is its own past. Remove `IAPL_NOINDEX` at launch as always — a site that still has it counts as a
|
||
non-public copy and sends nothing.
|
||
- **Staging and copies.** A site is active as soon as it enrols, so a staging site sends real mail. A **copy of
|
||
production's database** on a non-public site — a host that matches `iapl({ developmentHosts })` (built in:
|
||
`*.dev.netscale.pl`, Intecion's development domain; **no env needed**) or one with `IAPL_NOINDEX=1` — neither enrols nor
|
||
sends by itself (its data is production's) until an admin presses "Connect again", and never uses or touches
|
||
production's connection. **A copy on another host without `IAPL_NOINDEX=1` sends**, to the real addresses in its data: the plugin
|
||
cannot tell it from launch day (the doctor's deep run notes it). The safe set-up for a copy that must not send:
|
||
`iapl({ mail: { relay: false } })` or SMTP to a catcher ([email.md](./email.md) "Staging, copies and several
|
||
hosts").
|
||
- Several containers of one site share the database, so they share the token; a restore of an old database dump
|
||
brings back an old token — the site then enrols again by itself on its next e-mail.
|
||
|
||
### Email — Graph (deprecated since 1.17.0, removed in 2.0; only for sites that already use it)
|
||
|
||
```bash
|
||
GRAPH_TENANT_ID=<azure-tenant-id>
|
||
GRAPH_CLIENT_ID=<azure-app-client-id>
|
||
GRAPH_CLIENT_SECRET=<azure-app-secret>
|
||
GRAPH_SENDER=[email protected] # shared mailbox
|
||
```
|
||
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 (OPTIONAL in dev, recommended in production)
|
||
|
||
```bash
|
||
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= # usually EMPTY: media served through the app (§6, storage.md)
|
||
# or https://media.klient-media.com (custom domain, zone on Cloudflare)
|
||
```
|
||
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.
|
||
|
||
### Table — all variables read by the plugin
|
||
|
||
| Variable | Required | Layer | Description |
|
||
|---|---|---|---|
|
||
| `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 `iaplEnvRules` (R2 keys, `IAPL_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 | 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 only with `storage: { requirePublicUrl: true }`) | storage | media domain attached to the bucket; empty = media through the app (§6); dev: also the `/media` path |
|
||
| `IAPL_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. **`TURNSTILE_SECRET_KEY` is deprecated** — put the secret key into the panel (turnstile.md); the variable keeps working until a later, announced release |
|
||
| `INDEXNOW_KEY` | ⬜ | SEO | IndexNow key (takes precedence over the key from the panel) |
|
||
| `IAPL_COOKIE_SCAN_URL`, `IAPL_COOKIE_SCAN_TOKEN` | ⬜ (✅ prod with `iaplEnvRules({ cookieCrawl: true })`) | consent | cookie crawl (`cookieScanner.crawl`): the shared scanner service's URL and this site's token ([cookie-scanner.md](./cookie-scanner.md#browser-crawl)) |
|
||
| `IAPL_NOINDEX` | ⬜ | SEO | `1`/`true`/`yes` **on staging only** — the whole site is noindex (robots, meta, `X-Robots-Tag`) |
|
||
| `IAPL_DOCTOR_TOKEN` | ⬜ | ops | ≥ 32 characters turns on the `iapl-doctor` status endpoint `GET /api/ipal/doctor` (404 without it) — [doctor.md](./doctor.md) |
|
||
|
||
"✅ prod" = required by `iaplEnvRules({ 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.
|
||
|
||
**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 — always in the repo
|
||
|
||
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. BEFORE DEPLOY — checklist
|
||
|
||
- [ ] `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))
|
||
- [ ] `IAPL_NOINDEX` NOT set in production
|
||
|
||
---
|
||
|
||
## 3. BUILDING FOR PRODUCTION
|
||
|
||
### Build script (Next 16 + Payload)
|
||
|
||
```json
|
||
// 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 can be memory-hungry during the build;
|
||
3072 MB prevents OOM on smaller machines.
|
||
|
||
### Order: build → migrations → start
|
||
|
||
What Coolify runs (install/build/start commands in the app's build settings):
|
||
|
||
```bash
|
||
pnpm install --frozen-lockfile # exactly from the lockfile (repeatable build)
|
||
pnpm generate:types # types from collections
|
||
pnpm build # --webpack
|
||
# Postgres: pending migrations run when the NEW container starts, before it is healthy (§4.3)
|
||
pnpm start # production server, port 3000
|
||
```
|
||
|
||
---
|
||
|
||
## 3a. Pitfall: metadata in <body> instead of <head> (htmlLimitedBots)
|
||
|
||
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 = {
|
||
htmlLimitedBots:
|
||
/Googlebot|Google-InspectionTool|Bingbot|Yandex|DuckDuckBot|Screaming Frog|AhrefsBot|SemrushBot/i,
|
||
// ...
|
||
}
|
||
```
|
||
|
||
Check: `curl -A "Googlebot" URL | grep canonical` — it must be in `<head>`.
|
||
Details and symptoms: seo.md (htmlLimitedBots section).
|
||
|
||
## 3a2. ISR — page cache (metadata in head + speed)
|
||
|
||
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; or shorter, or on-demand
|
||
```
|
||
|
||
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; plugin globals — `iapl({ revalidatePath })`; your own globals —
|
||
`buildGlobalRevalidateHook`). See [seo.md](./seo.md), [hooks.md](./hooks.md).
|
||
|
||
## 3a3. SSG and database access at build time (IMPORTANT for SEO)
|
||
|
||
`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 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` covers only the pages collection (max 1000 documents per language) — entries
|
||
of content collections render on-demand (ISR).
|
||
|
||
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.**
|
||
|
||
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.
|
||
|
||
Check: after the build, `pnpm build` shows routes as `●` (SSG), not `ƒ`
|
||
(Dynamic). If `ƒ` despite generateStaticParams → the build had no database access.
|
||
|
||
## 3b. Pitfall: prerendering database-dependent routes (REQUIRED)
|
||
|
||
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**.
|
||
|
||
**Fix — `force-dynamic` on database-dependent routes:**
|
||
```ts
|
||
// app/sitemap.ts
|
||
export { sitemap as default } from '@/lib/content'
|
||
export const dynamic = 'force-dynamic' // generate at runtime, not at build time
|
||
```
|
||
|
||
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`
|
||
- other routes/pages reading the database during prerender → consider `force-dynamic` or
|
||
handle the database error (try/catch with a fallback)
|
||
|
||
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`.
|
||
|
||
**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).
|
||
|
||
**Local check** (simulate a missing database):
|
||
```bash
|
||
DATABASE_URI=mongodb://invalid-host:27017/test pnpm build
|
||
# the build must pass (exit code 0) despite the unreachable database
|
||
```
|
||
|
||
## 4. HOSTING — Coolify
|
||
|
||
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.
|
||
|
||
### 4.1 Application and domains
|
||
|
||
- **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.
|
||
|
||
### 4.2a Database names (VERY IMPORTANT)
|
||
|
||
Every project uses the same names, on MongoDB and Postgres: the site's domain **with the dots removed**, plus
|
||
`_prod` (production) or `_dev` (development / staging). No other suffixes, no `payload`, `test` or `db1`.
|
||
|
||
| Site | Production | Development |
|
||
|---|---|---|
|
||
| `intecion.com` | `intecioncom_prod` | `intecioncom_dev` |
|
||
| `architektimprez.pl` | `architektimprezpl_prod` | `architektimprezpl_dev` |
|
||
|
||
- The name is the path of `DATABASE_URI`: `mongodb://user:pass@mongo:27017/intecioncom_prod?authSource=admin`,
|
||
`postgres://user:pass@db:5432/intecioncom_prod` (the Postgres database name, not the user or the schema).
|
||
- In Coolify: create the database resource with that database name (Postgres "Initial database", or the name in the
|
||
Mongo connection string), and set `DATABASE_URI` on the app to it.
|
||
- A leading `www.` is not part of the name; a hyphen in the domain stays (quote the name in SQL:
|
||
`CREATE DATABASE "my-sitepl_prod"`).
|
||
- **Check:** `iaplEnvRules({ databaseName: true })` warns at startup (never fails) when the name in `DATABASE_URI`
|
||
does not match the domain in `NEXT_PUBLIC_SERVER_URL` (skipped for localhost). `{ domain: 'intecion.com' }` sets the
|
||
domain, `{ warn }` replaces the console warning; leave the option out to turn the check off. Helpers:
|
||
`databaseNamesFor`, `databaseNameFromUri`, `checkDatabaseName` from `@intecion/ipal-kit/env` (env.md).
|
||
|
||
### 4.2 Environment variables — where and when
|
||
|
||
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).
|
||
|
||
| 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`, `IAPL_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` |
|
||
| `IAPL_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 (`iapl-migrate-fields` skill). Take a
|
||
**Backup now** (§4.6) before a large migration.
|
||
|
||
### 4.3a Postgres: the connection pool
|
||
|
||
Payload holds one pool connection for the whole of a transaction (a form submission, "forgot password", a save in
|
||
the panel). Code inside it that runs **without** the transaction's `req` needs a **second** connection: Payload's own
|
||
"forgot password" (it reserves the request interval outside the transaction), an e-mail adapter reading its settings,
|
||
`payload.kv`, a project hook that calls the Local API without `req`. With the default pool of 10, **ten such requests
|
||
at the same moment held all ten connections and each waited for an eleventh — the whole site stopped, for good**
|
||
(measured on 1.16.8 and the 1.17.0 branch: 12 form submissions or 12 "forgot password" requests at once, an ordinary
|
||
page got no answer).
|
||
|
||
Since 1.17.0 the plugin keeps a few connections free of transactions (`connectionReserve`):
|
||
|
||
- at most `pool size − reserve` transactions are open at once; the next one waits for a place — its request is
|
||
slower, nothing stops. Default reserve: a fifth of the pool, at least 2 (1 in a pool of fewer than 4): with the
|
||
default pool of 10, eight transactions at once and two connections for everything else;
|
||
- a transaction begun **inside** another one — a hook that calls the Local API without `req` writes in a
|
||
transaction of its own while its caller's is open — does not queue: it takes no place, because its caller cannot
|
||
finish without it. It may use the reserve but the last connection (a second level inside it that one too), so one
|
||
connection stays free for the queries outside transactions. "Inside" is told by a mark the plugin sets when a
|
||
transaction begins (`AsyncLocalStorage`); in case the mark is lost on the way, a queue that has not moved for a
|
||
second (`RESERVE_ESCAPE_MS`) lets its newest waiter use the reserve, all but the last connection;
|
||
- form e-mails go out **after** the submission's transaction commits ([forms.md](./forms.md) "When e-mails go out"),
|
||
and so do Payload's own "forgot password" and "verify your e-mail" sent through `mailAdapter()`
|
||
(`mail.accountMailAfterCommit`, default on): a slow or hanging mail server holds no connection and no place; the
|
||
request still ends when the mail is out. A rolled-back operation sends nothing.
|
||
|
||
Measured on Postgres 17, default pool of 10 (`test/transactionPool*.test.ts`):
|
||
|
||
| At the same moment | 1.16.8 / `connectionReserve: false` | 1.17.0 |
|
||
|---|---|---|
|
||
| 12 or 30 form submissions, or 12 or 30 "forgot password" | site stops for good, pages too | all finish, a page answers in milliseconds |
|
||
| 9 / 12 / 30 submissions whose hook writes without `req` | 9 finish (363 ms); 12 and 30 stop the site | all finish (under 2 s) |
|
||
| 30 "forgot password" + 30 submissions, the mail service hanging (10 s budget a send) | site stops for good | all finish in about 11 s (one budget); with the reset mail inside its transaction (`accountMailAfterCommit: false`) the last waited 43.5 s |
|
||
| the same with an SMTP server that never answers (2 s time-outs in the test) | site stops for good | all finish in a few seconds |
|
||
|
||
```ts
|
||
iapl({ connectionReserve: 3 }) // keep three connections free
|
||
iapl({ connectionReserve: false }) // no limit, as before 1.17.0 (not recommended)
|
||
iapl({ mail: { accountMailAfterCommit: false } }) // "forgot password" mail inside its transaction, as before
|
||
```
|
||
|
||
MongoDB, SQLite and other adapters without a pool: no effect. A larger pool (`postgresAdapter({ pool: { max: 20 } })`)
|
||
moves the reserve with it; the Postgres server's own `max_connections` must allow every instance's pool.
|
||
Without `iapl()` (building blocks only): `onInit: (payload) => { reserveConnections(payload) }`.
|
||
Building blocks: `reserveConnections`, `watchTransactions`, `afterCommit` (run work right after a transaction
|
||
commits), `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (for a health or debug route:
|
||
`{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`; for account mail
|
||
`withAccountMailAfterCommit(collection)` (what the plugin does to every auth collection: wraps its
|
||
`generateEmailSubject`, which Payload calls with the request and the token right before the send),
|
||
`sendAccountMailAfterCommit(message, send)` (what an e-mail adapter of your own calls first), `holdAccountMail`,
|
||
`releaseAccountMail`. Still true: a hook that writes without `req` is a transaction of its own — it is not rolled
|
||
back with its caller's. Pass `req`.
|
||
|
||
**Check** (staging, Postgres): send 30 submissions of a form at once (or 30 "forgot password" requests for different
|
||
accounts) while loading a page — the page answers at once, every request finishes. `transactionWatchState(payload)`
|
||
shows `{ active, nested, waiting, reserve }`.
|
||
|
||
### 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' // never prerender/cache health
|
||
```
|
||
|
||
Custom settings — `createHealthRoute` directly:
|
||
|
||
```ts
|
||
import { createHealthRoute } from '@intecion/ipal-kit'
|
||
import { getCachedPayload } from '@/lib/content'
|
||
export const dynamic = 'force-dynamic'
|
||
export const GET = createHealthRoute({ getCachedPayload, collection: 'pages' })
|
||
```
|
||
|
||
| Option | Default | Description |
|
||
|---|---|---|
|
||
| `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 |
|
||
|
||
Response (`content-type: application/json`, `cache-control: no-store`):
|
||
- 200: `{ status: 'ok', db: 'up', timestamp, tookMs, …extra }`
|
||
- 503: `{ status: 'error', db: 'down', timestamp, tookMs }` — no error details (they go to the
|
||
server log: `[iapl] createHealthRoute: database unreachable`). An exception from `extra` also gives `db: 'down'`.
|
||
|
||
**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).
|
||
|
||
### 4.5 Rollback
|
||
|
||
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.
|
||
|
||
### 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;
|
||
4. `echo $?` — `0` after the summary means done. `1` with `[seed] ended before Payload initialized` (or `… before the
|
||
seed finished`) means the run stopped early and silently would have looked like a success — the seed's
|
||
`guardSeedExit()` caught it (seeding.md); run it again.
|
||
|
||
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.
|
||
|
||
### Form files (`forms.attachments`)
|
||
|
||
Files on forms are e-mailed, not stored — **no volume and no bucket** for them. What the deploy needs:
|
||
|
||
- **Request size.** The browser posts a form with a file to `/api/ipal/forms/submit` (up to `maxTotalMB`, 10 MB by
|
||
default, plus the answers). Coolify's Traefik and Caddy have no body limit by default. An nginx in front needs
|
||
`client_max_body_size 12m;`. Cloudflare (proxied) allows 100 MB. Next's Server Action limit does not apply, and
|
||
the i18n proxy must keep `/api` out of its matcher (the default one does).
|
||
- **Time.** The request stays open while the file uploads and the e-mail is sent. On a slow connection a 10 MB
|
||
upload can take over a minute — check the proxy's read timeout (Traefik: `respondingTimeouts.readTimeout` of the
|
||
entry point) if visitors on mobile networks report failures. Not measured by the plugin's tests; verify once on
|
||
the real server with a throttled upload. The plugin itself gives an upload up after 30 s without a byte and
|
||
after 5 minutes in total (`attachments.submit.idleTimeoutMs` / `timeoutMs`), so a dropped connection never
|
||
holds a slot.
|
||
- **Memory.** A file is held in memory while it is checked and sent (about 2.4 × its size); at most two file
|
||
submissions run at once per instance (`attachments.maxConcurrent`).
|
||
- **Mail.** Send the test e-mail with the 10 MB file after every change of mail provider
|
||
([email.md](./email.md) "Attachments").
|
||
|
||
### Integrations in the panel
|
||
|
||
Mail (the mail service, 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. AFTER DEPLOY — checks
|
||
|
||
- [ ] Home page `/` redirects to a locale (`/pl`)
|
||
- [ ] Panel `/admin` works, login OK
|
||
- [ ] The form sends (test from the panel: Send test)
|
||
- [ ] Forms with a File field: the test e-mail with the 10 MB file arrives; a real submission with a file arrives with the attachment
|
||
- [ ] 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 — records to add to the zone
|
||
|
||
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.
|
||
|
||
| # | Purpose | Record | Value | Check |
|
||
|---|---|---|---|---|
|
||
| 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) |
|
||
|
||
**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;
|
||
- **The Intecion mail service** (the default) → From is always `notification@webservices.intecion.net`:
|
||
SPF/DKIM/DMARC are Intecion's, set once for that domain. **Nothing is added to the client's DNS zone for it**; the
|
||
address from the panel goes into Reply-To;
|
||
- **Graph** transport (deprecated) → 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.
|
||
|
||
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 (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:
|
||
|
||
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); `iaplEnvRules({ storage: true })` accepts an
|
||
empty `R2_PUBLIC_URL` (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.
|
||
|
||
**Cookie checker (once per team, not per site):** `cookie-crawler.<team domain>` → `A`/`AAAA` to the Coolify server running the scanner service ([cookie-scanner.md](./cookie-scanner.md#scanner-service-on-coolify)). A site using `cookieScanner.crawl` needs no record of its own.
|
||
|
||
**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).
|
||
|
||
---
|
||
|
||
## WHY THIS MATTERS
|
||
|
||
- **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
|