Files

213 lines
11 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# env — validating environment variables at startup
Catches a misconfigured deploy at startup, with one readable message listing
ALL the gaps at once — instead of a cryptic crash somewhere halfway through the
build (`getaddrinfo ENOTFOUND`) or at runtime. Fail fast.
Related: [PROGRAMISTA.md §3–4](./dev/PROGRAMISTA.md), [storage.md](./storage.md),
[forms.md](./forms.md), [deployment.md](./deployment.md).
**Where the values live:** dev → `.env` (never committed; `.env.example` without values is). Production → the
Coolify application → **Environment Variables**, each marked for build time and/or runtime: `NEXT_PUBLIC_*` at
build time (inlined by `next build`) and runtime; secrets (`PAYLOAD_SECRET`, `R2_*`, `GRAPH_*`, …) at runtime;
`DATABASE_URI` / `PAYLOAD_SECRET` also at build time only when the build prerenders from the database. Table and
details: [deployment.md §4.2](./deployment.md). A changed variable needs a redeploy.
## Why no zod
The plugin deliberately does NOT pull in `zod`. Forcing a validation library on every
project is an imposed dependency (breaks A0 "no imposed dependencies").
`assertEnv` is a small, zero-dependency validator that does exactly what is
needed.
## Integration — one line at startup
The best place is `instrumentation.ts` (Next calls `register()` once at
server startup):
```ts
// src/instrumentation.ts
import { assertEnv, iaplEnvRules } from '@intecion/ipal-kit/env'
export function register() {
if (process.env.NEXT_RUNTIME !== 'nodejs') return // Edge: no server process.env
assertEnv(iaplEnvRules({ storage: true, emailGraph: true, turnstile: true }))
}
```
> **Import from `@intecion/ipal-kit/env`, not from the root.** Next compiles
> `instrumentation.ts` for Edge too. The package root pulls in Payload, `file-type`,
> `fs` — Turbopack fails (`Export fileTypeFromFile doesn't exist in target module`).
> `/env` is only the validator, zero dependencies. The root still exports `assertEnv`
> and `iaplEnvRules` (e.g. for `payload.config.ts`).
**Turn off / override / extend:** validation is fully opt-in — the plugin never calls
`assertEnv` by itself; without this line nothing is checked. Replace any preset rule by filtering
the array (`iaplEnvRules(…).filter((r) => r.name !== 'X')`), add your own (spread below), or
write the whole set by hand.
Alternatively at the top of `payload.config.ts` (it loads both at build time and at
runtime). Server-side only (reads `process.env`) — do NOT import it
into a client component.
## iaplEnvRules — ready-made schema for the stack (opt-in)
Builds the rule set from the features the project actually uses — a site on
local disk is not forced to set `R2_*`, a site without forms is not forced to set Turnstile.
It is not a rigid required set (A0: the plugin does not demand config you do not
use).
```ts
iaplEnvRules({
storage?: boolean | { requirePublicUrl?: boolean }, // R2_* (R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ENDPOINT; R2_PUBLIC_URL optional)
emailGraph?: boolean, // DEPRECATED (Microsoft Graph, removed in 2.0): GRAPH_* (GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER). E-mail needs no variable: email.md
cookieCrawl?: boolean, // IAPL_COOKIE_SCAN_URL (url), IAPL_COOKIE_SCAN_TOKEN (≥ 16 chars) — required in production; cookieScanner.crawl (cookie-scanner.md)
ipHeader?: boolean, // IAPL_IP_HEADER — required in production, optional outside it (header name [a-z0-9-])
turnstile?: boolean | { siteKeyVar?: string; secretVar?: string }, // NEXT_PUBLIC_TURNSTILE_SITE_KEY, TURNSTILE_SECRET_KEY
serverUrlVar?: string, // default 'NEXT_PUBLIC_SERVER_URL'
secretVar?: string, // default 'PAYLOAD_SECRET'
secretMinLength?: number, // default 32 — minimum PAYLOAD_SECRET length, checked in production only; 0 = off
databaseVar?: string, // default 'DATABASE_URI'
databaseName?: boolean | { domain?: string; warn?: (message: string) => void },
// WARN (never fail) when the DATABASE_URI database is not <domain without dots>_prod / _dev
})
```
Always (core): `DATABASE_URI`, `PAYLOAD_SECRET` (in production at least `secretMinLength` = 32 characters), `NEXT_PUBLIC_SERVER_URL` (URL),
`NODE_ENV` (optional, oneOf `development`/`production`/`test`). The names `R2_*` / `GRAPH_*` /
`NEXT_PUBLIC_SERVER_URL` / `IAPL_IP_HEADER` / Turnstile match what the plugin modules
read; DB/secret are Payload variables — their names can be overridden.
**`storage: true` — when R2_* are required** (evaluated when `iaplEnvRules` is called):
- `NODE_ENV=production` → the 4 keys (`R2_BUCKET`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_ENDPOINT`);
- outside production, when any of the 4 keys is set → all 4 (all or none);
- outside production without keys → none required (local disk); `R2_PUBLIC_URL` alone passes
(read-only mode, storage.md).
- `R2_PUBLIC_URL` is **optional**: empty = media served by the app. When set, it must be an absolute URL in
production. `storage: { requirePublicUrl: true }` requires it wherever the 4 keys are required (a project
that always uses a media domain).
**`turnstile: true`** makes both Turnstile variables **required**, even though the plugin takes the keys
from the panel first (Site integrations) and env is only a fallback — turn it on only when you keep the keys
in env.
**Names.** The plugin's own variables are `IAPL_<NAME>` since 1.17.0. A deploy that still sets `IPAL_<NAME>`
keeps working: `IAPL_…` is read first, `IPAL_…` when it is missing or empty (also by `assertEnv(iaplEnvRules())`,
whose messages name the `IAPL_` spelling). Set one of the two; `iapl-doctor` (`legacy-names`) warns when both are
set with different values. For your own rules: `{ name: 'NEW_NAME', aliases: ['OLD_NAME'] }` reads the old
name the same way. `ipalEnvRules` is the old name of `iaplEnvRules` and still exported.
Reading one of the plugin's variables in your own code: `readEnv('IAPL_NOINDEX')` (from `@intecion/ipal-kit/env` or the
root) returns the `IAPL_` value, else the `IPAL_` one; `legacyEnvName('IAPL_NOINDEX')` is `'IPAL_NOINDEX'`. The exported
name constants `COOKIE_SCAN_URL_ENV` and `COOKIE_SCAN_TOKEN_ENV` keep their values (`'IPAL_COOKIE_SCAN_URL'`,
`'IPAL_COOKIE_SCAN_TOKEN'`): they are the old names. The new ones are `IAPL_COOKIE_SCAN_URL_ENV` and
`IAPL_COOKIE_SCAN_TOKEN_ENV`; read them with `readEnv`, which falls back.
An **empty** new variable does not switch the old one off: `IAPL_NOINDEX=` beside `IPAL_NOINDEX=1` is still noindex
(empty counts as not set, and the old name is read). When a staging copy becomes production, remove the variable
under **both** spellings.
`ipalEnvRules()` and `iaplEnvRules()` are not the same list: the old one names the plugin's variables `IPAL_<NAME>`
(alias `IAPL_<NAME>`), the new one the other way round, so project code that adapts the rules by `rule.name` keeps
finding the names it was written for. Both accept both spellings in the environment.
The plugin also reads (outside the preset — add your own rules if you want to validate them):
`INDEXNOW_KEY` (seo.md), `IAPL_NOINDEX` (`1`/`true`/`yes` — staging, seo.md), `IAPL_DOCTOR_TOKEN` (≥ 32 characters —
turns `GET /api/ipal/doctor` on, doctor.md). Full table:
[deployment.md](./deployment.md).
Extending with your own variables — spread:
```ts
assertEnv([
...iaplEnvRules({ storage: true }),
{ name: 'MY_API_KEY', description: 'Key for integration X' },
])
```
### Database names — `databaseName`
The naming rule (deployment.md §4.2a): the site's domain with the dots removed, plus `_prod` / `_dev` —
`intecion.com` → `intecioncom_prod` / `intecioncom_dev`. `iaplEnvRules({ databaseName: true })` adds a check that
only **warns** (console, or your `warn`) when the database in `DATABASE_URI` breaks it. The domain comes from
`NEXT_PUBLIC_SERVER_URL` in `process.env` (localhost and dotless hosts are skipped) or from `{ domain }`.
```ts
import { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from '@intecion/ipal-kit/env'
databaseNamesFor('https://www.intecion.com') // { prod: 'intecioncom_prod', dev: 'intecioncom_dev' }
databaseNameFromUri('postgres://u:p@db:5432/intecioncom_prod') // 'intecioncom_prod' (null for file:/no name)
checkDatabaseName({ databaseUri: process.env.DATABASE_URI, domain: 'intecion.com' }) // warning text or null
```
## assertEnv — the validator
```ts
assertEnv(rules: EnvRule[], options?: { env?, label? }): void
```
Collects ALL problems and throws one aggregated `Error`. With no
problems it does nothing. `options.env` (default `process.env`) makes testing easier;
`options.label` changes the prefix (default `[iapl]`).
### EnvRule
```ts
type EnvRule = {
name: string
required?: boolean // default true; false = validate only when present
kind?: 'string' | 'url' | 'number' | 'port' | 'boolean' | 'email' // default 'string'
oneOf?: readonly string[]
description?: string // shown in the error — what this variable is for
validate?: (value: string) => string | true // custom rule
}
```
By hand, without the preset:
```ts
assertEnv([
{ name: 'DATABASE_URI', description: 'MongoDB connection string' },
{ name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },
{ name: 'NODE_ENV', required: false, oneOf: ['development', 'production', 'test'] },
{ name: 'SMTP_PORT', required: false, kind: 'port' },
])
```
### Sample message (preset `iaplEnvRules()`)
```
[iapl] Environment validation failed (3 problems):
• DATABASE_URI is required but missing — Database connection string (e.g. MongoDB URI)
• NEXT_PUBLIC_SERVER_URL must be a valid URL (got "example.com") — Public site origin, e.g. https://example.com
• NODE_ENV must be one of: development, production, test (got "prod") — Node environment
Set these in your environment (Coolify → Environment, or .env) and redeploy.
```
You see all the gaps at once — you do not fix them one by one over several
redeploys.
## Exports
```ts
import { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules } from '@intecion/ipal-kit/env'
import type { EnvRule, EnvKind, AssertEnvOptions, IaplEnvFeatures } from '@intecion/ipal-kit/env'
```
## `R2_PUBLIC_URL` — production vs dev
`R2_PUBLIC_URL` is optional in `iaplEnvRules({ storage: true })`: our default is media served through the app
with `R2_PUBLIC_URL` **empty** (the client zones are not on Cloudflare — storage.md, deployment.md §6). When it is
set, **production** requires a full URL (`https://media.klient-media.com`). A project that always uses a media
domain requires it:
```ts
assertEnv(iaplEnvRules({ storage: { requirePublicUrl: true }, ipHeader: true }))
```
Outside production it allows a relative path
(`/media`) — `buildR2Storage` prepends `NEXT_PUBLIC_SERVER_URL` to it, CSP does not
add it (it is `'self'`), `MediaPreconnect` skips it. Dev without a bucket: do not set
`R2_*` at all — `storage: true` can stay (outside production without keys nothing is required),
media land on disk.