Files
ipal-kit/docs/dev/PROGRAMISTA.md
T
Radosław SmolińskiandClaude Fable 5.2 9143c132a3 Payload's colour-scheme client hints go to the admin only: withSecurityConfig outside withPayload
withPayload adds Accept-CH, Critical-CH and Vary: Sec-CH-Prefers-Color-Scheme for /:path*; Critical-CH makes
Chrome repeat the first document request of a visit to a public page. As the outer wrapper, withSecurityConfig
moves the three headers to /admin/:path* (adminClientHints: { route, sources } | false). Inside withPayload
nothing changes, so an unedited site behaves as before. Exports scopeColorSchemeClientHints,
adminClientHintSources, COLOR_SCHEME_CLIENT_HINT; doctor rule client-hints (info); reference site and starter
use the new order; e2e:built and the starter gate check it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 11:55:26 +01:00

76 KiB
Raw Blame History

PROGRAMISTA.md — install, new project, deployment, IAPL development

Who it is for: a human — a developer at the agency. Rules for writing code (for AI and for humans) are in AGENT.md; module APIs are in the module files (map in AGENT.md §12). This file is the process: how to set up, deploy and update a project, and how to release a new plugin version.

Building a project with an AI agent? Ready-made prompts, step by step: vibe.md.

0. MAIN RULE — the plugin helps, never limits

IAPL is a plugin: it helps projects, it never limits them.

  • Every module / feature can be turned off on its own.
  • Every default (access rules, fields, hooks, labels, routes, collections, globals) can be overridden — the project config wins.
  • Safe defaults, always with an option to relax them.
  • We export building blocks (helpers, builders, hooks), not only finished features.
  • We never force a dependency, route, UI or data shape where an option or an exported building block is enough.

Where the code does not meet this yet, the module docs say so plainly ("currently always added").

Contents: 0. Main rule · 1. Install · 2. New project · 3. Environment variables · 4. Deployment (Coolify) · 5. Compliance · 6. Updating an old project · 7. Troubleshooting · 8. IAPL development and publishing · 9. Git and Gitea


1. INSTALLING IAPL IN A PROJECT

.npmrc in the project root (commit it — it holds no secret):

legacy-peer-deps=true
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/

This rule applies only to the @intecion/* scope — everything else (react, payload…) still comes from npm. The registry is public for reading, so install needs no token.

pnpm add @intecion/ipal-kit
pnpm add @payloadcms/plugin-seo @payloadcms/plugin-form-builder   # peer dependencies
pnpm add @clocklimited/[email protected]      # 2FA (optional peer, but required unless twoFactor: false)
pnpm add @payloadcms/storage-s3                      # optional peer — only when media live in R2
pnpm add tailwindcss @tailwindcss/postcss
pnpm exec iapl-skills    # agent skills + pointer to the guide in AGENTS.md / CLAUDE.md (§2.1a)

nodemailer, lucide-react (^0.400.0 = only 0.400.x), slugify, server-only are regular dependencies of the plugin — they install with it, do not add them. The other peers (payload, @payloadcms/next, @payloadcms/ui, @payloadcms/richtext-lexical, next, react) come from create-payload-app. If the project uses lucide-react itself, keep it at ~0.400.0 (another version = two copies).

Never from git (git+https://…) — a path with a hash breaks the React Client Manifest (the plugin's 'use client' components fail at runtime).

@payloadcms/* versions must match payload exactly — otherwise you get an empty SEO tab, a missing Forms collection or a crash. In package.json:

"pnpm": {
  "overrides": {
    "payload": "3.94.1",
    "@payloadcms/ui": "3.94.1",
    "@payloadcms/next": "3.94.1",
    "@payloadcms/db-postgres": "3.94.1",
    "@payloadcms/richtext-lexical": "3.94.1",
    "@payloadcms/plugin-seo": "3.94.1",
    "@payloadcms/plugin-form-builder": "3.94.1",
    "@payloadcms/storage-s3": "3.94.1"
  }
}

(match the database adapter: db-postgres / db-mongodb). Then rm -rf node_modules pnpm-lock.yaml && pnpm install.

Build with webpack (Turbopack conflicts with withPayload):

"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"

Check that the registry responds:

curl -s -o /dev/null -w "%{http_code}\n" \
  https://git.intecion.net/api/packages/IntecionSoftware/npm/@intecion%2Fipal-kit   # 200

Updating to the latest version: pnpm up --latest @intecion/ipal-kit. Plain pnpm up @intecion/ipal-kit changes nothing when package.json has an exact version ("1.8.13") — it stays within the range. Then follow the "Requires project changes" sections of the CHANGELOG.

401 when fetching the package (ERR_PNPM_FETCH_401 … Unauthorized) even though the registry is public: ~/.npmrc has an old _authToken for git.intecion.net, and an invalid token also blocks reading. Remove that line (the token is needed only for publishing, §8.3) or run once: NPM_CONFIG_USERCONFIG=/dev/null pnpm up --latest @intecion/ipal-kit.


2. NEW PROJECT — ORDER

Fastest: one command. pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create <domain> generates the whole site from the reference site — questions, files, install, skills, first commit (project-starter.md). The order below is the manual path (an existing project, or what the command does not cover yet).

Pnpm, Node 22+, Next 16, Payload 3. The order matters.

2.1 Skeleton

npx create-payload-app@latest my-project     # Blank; Postgres or Mongo
cd my-project

Delete the starter (frontend)/layout.tsx and (frontend)/page.tsx — the root becomes the layout under [locale] (because <html lang> must know the language).

2.1a Skills and AGENTS.md

// project package.json
"scripts": {
  "iapl:skills": "iapl-skills"
}

Run pnpm exec iapl-skills after install and after every IAPL update; commit .agents/skills/. (iapl-skills is the package bin — without the script: pnpm exec iapl-skills; options --dest <dir>, --dry-run, --no-pointer, --external [ext-a,ext-b].) The command also adds to AGENTS.md a <!-- iapl:start -->…<!-- iapl:end --> block with a pointer to AGENT.md and the iapl-reference / iapl-setup skills, and creates a missing CLAUDE.md with the line @AGENTS.md. On later runs it replaces only the text between the markers. This way an agent that opens the project lands on the full guide right away — without a postinstall script (the package has none and never will). Project tsconfig.json: "exclude": ["node_modules", ".agents"] — the skills contain .ts/.tsx templates; without the exclusion tsc and next build check them as project code and fail (iapl-skills and iapl-audit warn about it). In the root, AGENTS.md follows the template from AGENT.md §13. List of skills: AGENT.md §14.

2.2 Locale — one source

// src/i18n.config.ts
import type { I18nConfig } from '@intecion/ipal-kit'

export const i18nConfig = {
  defaultLocale: 'pl',
  locales: [
    { code: 'pl', label: 'Polski' },
    { code: 'en', label: 'English' },
  ],
} as const satisfies I18nConfig

Single-language site: one locale, no [locale] folder — layout with i18nConfig.defaultLocale, createPageRoute / createNotFoundPage unchanged, Markdown in app/md/[[...slug]]/route.ts (i18n.md). Do not add [locale] "just in case" with one language — links would be without /pl, pages with /pl.

2.3 payload.config.ts

import { buildConfig } from 'payload'
import { buildR2Storage, iapl, mailAdapter } from '@intecion/ipal-kit'
import { payloadTotp } from '@clocklimited/payload-2fa'
import { s3Storage } from '@payloadcms/storage-s3'
import { i18nConfig } from '@/i18n.config'
import { contentConfig } from '@/content.config'
import { Pages } from '@/collections/Pages'
import { Media } from '@/collections/Media'

export default buildConfig({
  collections: [Pages, Media],               // iapl adds users (your own only for extra fields)
  email: mailAdapter(),                      // without it form-builder emails are not sent
  plugins: [
    iapl({
      i18n: i18nConfig,
      access: { authCollection: 'users' },
      pages: { slug: 'pages' },              // System pages (homepage, 404, policies)
      content: contentConfig,                // collections with an archive (blog…), optional
      seo: { collections: ['pages'] },
      forms: { redirectRelationships: ['pages'] },
      twoFactor: { issuer: 'Nazwa Klienta', plugin: payloadTotp },
      whiteLabel: true,                      // logo/name from Site settings in the admin panel
      indexNow: true,                        // publish → Bing / ChatGPT Search (production)
      consentLog: true,                      // proof of consent (GDPR Art. 7(1)), no personal data
      // adminRoute: '/its',                 // + move app/(payload)/admin → its and put `its` in the proxy matcher (§2.6)
    }),
    buildR2Storage(['media'], { s3Storage }),  // ALWAYS — R2 when all R2_* are in env, local disk without them
  ],
})

The mandatory feature set (SEO, GEO, R2, Turnstile, forms…) and how to check it: AGENT.md §0b. Code for all routes below (§2.7–2.9).

2.4 Collections, blocks, shared fields

  • Pages: title (localized), buildSlugField({ from: 'title' }), buildNoindexField(), buildSummaryField() (summary for AI — GEO), layout of type blocks (min. 1 block), trackSlugHistoryHook, buildRevalidateHook.
  • Media: upload with mimeTypes (images + PDF), alt (required, localized), normalizeFilenameHook, buildOptimizeUploadHook + buildOptimizeUploadField (oversized files, with consent), buildMediaPlaceholderHook + buildMediaPlaceholderField (blur/color for mediaImageProps) — media.md; R2 through buildR2Storage(['media'], { s3Storage }) — s3Storage from @payloadcms/storage-s3, injected (storage.md).
  • Fields from the plugin: links (buildLinkField, buildLinksField — links.md), section header and settings (buildSectionHeaderField, buildSectionSettingsField — blocks.md). The project holds only the visual UI primitives in src/components/ui/ (CMSLink on resolveLink, Button, Media, Section, SectionHeader) and src/components/forms/formClasses.ts — ready code in agent/skills/iapl-block/resources/section-code.md and iapl-form/resources/, rules in AGENT.md §6. Create them before the first block.

2.5 Tailwind

// postcss.config.mjs
export default { plugins: { '@tailwindcss/postcss': {} } }
/* src/app/(frontend)/styles.css */
@import "tailwindcss";
@import "@intecion/ipal-kit/fluid.css";   /* optional: fluid typography and spacing scale */
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";

@theme inline {
  --text-display: var(--ipal-fs-display);
  --text-h1: var(--ipal-fs-h1);
  --text-h2: var(--ipal-fs-h2);
  --text-h3: var(--ipal-fs-h3);
  --text-lead: var(--ipal-fs-lg);
  --spacing-section: var(--ipal-space-section);
  --spacing-gutter: var(--ipal-space-gutter);
  --spacing-gap: var(--ipal-space-gap);
}

fluid.css is only clamp() variables (360 → 1280 px, in rem) — classes text-h1, py-section, px-gutter. fluid-wide.css — the same variables, scaled up to 1920 px (13″ ≠ 27″); import one of the two. Both also have height and width variables: --ipal-hero-min-h, --ipal-fs-display-fit, --ipal-space-section-fit, --ipal-measure, --ipal-container (AGENT.md §6.11a). Override numbers from DESIGN.md in the project's :root (--ipal-fs-h1: clamp(…)); do not write the formulas from scratch. Without @source the plugin's components (cookie banner, Turnstile) have no styles. Colors of the plugin's components: --ipal-primary, --ipal-radius (consent.md).

Design-token standard (1.15.0, design-tokens.md) — new sites: styles.css imports fluid-wide.css, tokens.css, tailwind.css and ../../design/tokens.css (instead of the @theme inline above); the brand is src/design/tokens.ts → pnpm exec iapl-tokens; next/font variables --font-family-body / --font-family-heading. Components use the preset's utilities (bg-surface, text-fg, py-section).

2.6 Proxy (NOT middleware.ts)

// src/proxy.ts
import { NextResponse } from 'next/server'
import { createProxy } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'

// markdown: true (GEO) — /md/… passes without a language redirect, and a page
// fetched with `Accept: text/markdown` gets its Markdown version
export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true })

// Inline literal — Next analyzes it statically; importing a variable = proxy on /admin → 500
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }

Sets x-locale / x-pathname, the language cookie with consent, redirects /. The headers are for dynamic routes (API, route handlers) — in SSG/ISR pages, layouts and not-found.tsx do not read headers() (AGENT.md §4.6).

2.7 Data layer — one source

// src/lib/content.ts — the ONLY place for configuration: data, routes, links, layout
import { createContentHelpers } from '@intecion/ipal-kit'
import config from '@/payload.config'
import { i18nConfig } from '@/i18n.config'
import { contentConfig } from '@/content.config'

export const {
  // data
  getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, getNotFoundPage,
  generatePageMetadata, generateStaticParams, getPageJsonLd, resolvePageRedirect, i18n,
  // layout, forms, links
  getSiteShell, getFormTexts, getLinkOptions, getHomeSlug, resolveLink, resolveNav, getSystemLinks,
  // routes (re-exported in app/)
  sitemap, sitemapRoute, robots, manifest, llmsRoute, llmsFullRoute, markdownRoute,
  mcpGET, mcpPOST, healthRoute, indexNowKeyRoute,
} = createContentHelpers({
  config,
  content: contentConfig,
  i18n: i18nConfig,
  baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
  markdownAlternate: true,          // GEO: <link rel="alternate" type="text/markdown"> on every page
  summaryField: 'aiSummary',        // llms.txt and MCP take the AI description from buildSummaryField
  mcp: { serverName: '<client>-site' },
  // pageJsonLd: { faq: (doc) => …map the FAQ block to { question, answer }… },
  // siteJsonLd: async ({ settings, baseUrl, locale }) => [buildLocalBusinessJsonLd({…})],  // local business
})

Everything is computed only on first use and cached per request. You can skip any function and build the page from lower-level blocks (createPageMetadata, createLlmsTxtRoute, createMcpRoute… — seo.md, mcp.md) — the plugin forces nothing.

2.8 Routes

// src/app/(frontend)/[locale]/layout.tsx
import { notFound } from 'next/navigation'
import { CookieBanner } from '@intecion/ipal-kit/client'
import { SiteProviders } from '@intecion/ipal-kit/rsc'
import { getConfiguredLocales, getSiteShell } from '@/lib/content'
import '../styles.css'

type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }

export default async function LocaleLayout({ children, params }: Props) {
  const { locale } = await params
  if (!(await getConfiguredLocales()).includes(locale)) notFound()
  const shell = await getSiteShell(locale)   // consent, analytics, Turnstile, site JSON-LD, Site settings
  return (
    <html lang={locale}>
      {/* NO <head> — Next manages it itself */}
      <body>
        <SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>
          {/* <Header …/> */}
          <main>{children}</main>
          {/* <Footer …/> */}
        </SiteProviders>
      </body>
    </html>
  )
}

SiteProviders wires things in the right order: MediaPreconnect, JsonLdGraph (WebSite + Organization from Site settings), ConsentProvider → TurnstileProvider (always — it turns itself off without keys) → banner, CookieButton, Analytics (inside consent). It adds no markup. You can change or turn off every part: banner={<CookieBanner classNames={…} />} / false, cookieButton, analytics={{ defer: true }} / false, jsonLd={[buildNavigationJsonLd(…)]}, cookieMap, preconnect={false}. A fully custom layout: pass the same data from shell to the providers (consent.md).

Pick the consent settings window with the banner's settings prop: 'inline' (default — categories in the bar), 'modal' (small window in the center) or 'detailed' (large window: each category with a switch, a description and an expandable list of cookies from Cookies → Cookie list). Example: banner={<CookieBanner equalChoice controls="switch" settings="detailed" />} — description: consent.md, the settings="detailed" section.

// src/app/(frontend)/[locale]/[[...slug]]/page.tsx — DOUBLE brackets
import { notFound, permanentRedirect } from 'next/navigation'
import { createPageRoute } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
import { sendForm } from '../actions'

export const revalidate = 3600   // ISR — a literal in the file (Next reads it statically)

const route = createPageRoute(content, {
  blocks: blockRegistry,
  notFound, permanentRedirect,                       // injected from next/navigation
  blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
  // render: ({ route, blocks }) => route.type === 'archive' ? <Archive … /> : undefined,
})
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams   // SSG → synchronous <head>

createPageRoute: route (resolveRoute), old slug → 308 (resolvePageRedirect), 404, metadata, generateStaticParams, page JSON-LD (getPageJsonLd, turn off: jsonLd: false) and blocks with locale + blockProps. No searchParams — an archive with pagination (?page=) is a separate route or deliberately dynamic (pages.md). Custom page: the same helpers by hand (pages.md).

// src/app/(frontend)/[locale]/notFoundView.ts — 404 content from the admin panel in one language (server action, since 1.12.0)
'use server'
import { renderNotFoundView } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'

export async function loadNotFoundView(locale: string) {
  return renderNotFoundView(content, { blocks: blockRegistry }, locale)
}

// src/app/(frontend)/[locale]/not-found.tsx — 404 in the URL's language, no headers(); content loads only on a 404,
// not in the RSC data of every page (pages.md → why it is lazy)
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { loadNotFoundView } from './notFoundView'

export default createNotFoundPage(content, { load: loadNotFoundView })
// SEO / GEO / ops routes — each one is a re-export, the configuration lives in lib/content.ts
// src/app/sitemap.xml/route.ts — XML for Google, human-readable styling from the plugin (nothing in /public)
export { sitemapRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

// src/app/robots.ts — robots from code + the AI crawler policy from Site settings → Search engines
export { getRobots as default } from '@/lib/content'
export const dynamic = 'force-dynamic'

// src/app/manifest.ts
export { manifest as default } from '@/lib/content'
export const dynamic = 'force-dynamic'

// ---- GEO: all of the below are mandatory (AGENT.md §0b.5–8) ----
// src/app/llms.txt/route.ts           (+ llms-full.txt/route.ts: llmsFullRoute)
export { llmsRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

// src/app/md/[locale]/[[...slug]]/route.ts — every page as Markdown (noindex + canonical to the HTML)
export { markdownRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

// src/app/indexnow-key.txt/route.ts — IndexNow key (from Site integrations or INDEXNOW_KEY)
export { indexNowKeyRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

// src/app/api/mcp/route.ts — public MCP server (AI browses the site)
export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'
export const dynamic = 'force-dynamic'

// src/app/api/health/route.ts
export { healthRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

One sitemap: sitemap.xml/route.ts or sitemap.ts — never both. The sitemap heading = "XML Sitemap", below it "Technology by Intecion.com"; change it with createContentHelpers({ sitemapStyle }) (seo.md).

2.9 next.config.ts and instrumentation.ts

// next.config.ts
import { withPayload } from '@payloadcms/next/withPayload'
import { buildImagesConfig, buildSecurityHeaders, buildUploadSecurityHeaders } from '@intecion/ipal-kit'

const securityHeaders = buildSecurityHeaders({ hsts: process.env.NODE_ENV === 'production' })

export default withPayload({
  images: { ...buildImagesConfig() },   // AVIF/WebP, R2 domain (R2_PUBLIC_URL), 31-day cache
  htmlLimitedBots:
    /Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i,
  async headers() {
    return [{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]
  },
})

CSP (buildCsp) — first report-only, then enforce after checking the console (security.md). src/instrumentation.ts: assertEnv(iaplEnvRules({...})) from @intecion/ipal-kit/env, only when NEXT_RUNTIME === 'nodejs' (env.md).

2.10 Generate and start

pnpm generate:types
pnpm payload generate:importmap     # after every change to admin components
pnpm dev

2.11 Configuration in the admin panel (/admin)

  1. First user (admin) + 2FA setup.
  2. Site settings → General — site name, logo, favicon (PNG).
  3. Pages — the homepage with a title in every language (empty EN slug = 404 on /en).
  4. Site settings → System pages — Homepage (without it /pl → 404), 404, policies; archives of content collections.
  5. Cookies — banner texts per language; Cookies (list from the scan, iapl-consent-check) and Detail labels (captions of the list in the settings="detailed" window) — also in every language.
  6. Notifications — form messages per language.
  7. Site integrations — SMTP/Graph (From Name, From Address), Turnstile, analytics/pixel IDs, IndexNow (integrations.md). Mail / Turnstile problems show as an alert on the dashboard and a banner on the tab.

/ → redirect to /pl. Turnstile test keys: site 1x00000000000000000000AA, secret 1x0000000000000000000000000000000AA.


3. ENVIRONMENT VARIABLES

Variable Required Description
DATABASE_URI ✅ Postgres / Mongo (dev can use SQLite)
PAYLOAD_SECRET ✅ random, ≥32 characters, different in production — iaplEnvRules checks the length in production (secretMinLength, default 32, 0 = off)
NEXT_PUBLIC_SERVER_URL ✅ public URL (canonical, hreflang, OG); without it links are relative
GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER ⬜ email through Microsoft Graph
R2_BUCKET, R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY ✅ prod media in Cloudflare R2 — always in production (missing → container disk, files vanish on redeploy without a volume); in dev they can be empty (storage.md)
R2_PUBLIC_URL ⬜ empty by default — media served through the app (/api/media/file/…); a media domain whose zone is on Cloudflare only for media-heavy sites (storage.md, deployment.md §6); in dev alone = read-only media
NODE_ENV ⬜ development / production / test — production tightens the iaplEnvRules rules (R2, IAPL_IP_HEADER)
IAPL_NOINDEX ⬜ 1 only on staging / preview — the whole site out of Google (robots, meta, header)
INDEXNOW_KEY ⬜ IndexNow key, when not set in the admin panel (Site integrations → IndexNow generates one itself)
IAPL_IP_HEADER ✅ prod header with the real IP for the rate limit: cf-connecting-ip behind Cloudflare, x-forwarded-for behind plain Traefik/nginx (forms.md)
NEXT_PUBLIC_TURNSTILE_SITE_KEY, TURNSTILE_SECRET_KEY ⬜ fallback when the Turnstile keys are not in the admin panel (iaplEnvRules({ turnstile: true }) makes them required)

Full list and validation at startup: env.md, deployment.md.

R2 example:

R2_BUCKET=klient-media
R2_ENDPOINT=https://<ACCOUNT_ID>.r2.cloudflarestorage.com
R2_ACCESS_KEY_ID=<access-key>
R2_SECRET_ACCESS_KEY=<secret-key>
R2_PUBLIC_URL=                             # empty = media through the app (default)

Rules: secrets only in .env (dev) and the Coolify app's Environment Variables (prod — build time vs runtime: deployment.md §4.2), never in the repo. .env.example (no values) always in the repo. Content the editor can change → admin panel, not env. Infrastructure (R2, Graph, database) → env, not the admin panel.


4. DEPLOYMENT (Coolify)

Every project runs on Coolify on our servers; we also run the DNS zones. Full procedure: deployment.md §4 (Coolify) and §6 (DNS).

4.1 Before deploying

  • pnpm build passes locally (not only dev)
  • env in the Coolify app: NEXT_PUBLIC_* at build time + runtime, secrets at runtime, DATABASE_URI / PAYLOAD_SECRET also at build time when pages are prerendered (§4.3; deployment.md §4.2)
  • NEXT_PUBLIC_SERVER_URL = production URL, production PAYLOAD_SECRET
  • HSTS on; media in R2 (served through the app, R2_PUBLIC_URL empty, Media with public read) or a persistent volume — local media vanish on redeploy
  • Postgres: committed migrations, run on container start (prodMigrations); scheduled backups to S3/R2
  • policies + cookie banner (§5)

4.2 Order

  1. DNS: A/AAAA apex + www → the Coolify server; CAA (if any) allows letsencrypt.org (deployment.md §6).
  2. Coolify: database resource (Postgres/Mongo) + backups schedule to S3/R2 (deployment.md §4.6).
  3. Coolify application from the Git repo: port 3000, domains https://klient.pl,https://www.klient.pl, www ↔ apex redirect matching NEXT_PUBLIC_SERVER_URL, env variables, health check /api/health (deployment.md §4.1–4.4).
  4. Deploy. What runs:
pnpm install --frozen-lockfile
pnpm generate:types
pnpm build
pnpm start                  # Postgres: pending migrations run here, before the container is healthy

Migrations are not Coolify Pre-/Post-deployment commands (pre runs in the old container and is skipped on the first deploy; post runs after traffic has switched). Use postgresAdapter({ …, prodMigrations: migrations }) or the start command pnpm payload migrate && pnpm start; keep migrations backward compatible (the old container serves during the rolling update). Mongo: no migrations. Details: deployment.md §4.3.

4.3 Database at build time

  • The build sees the database → generateStaticParams prerenders pages (SSG, ●), <head> is complete. This is what we want: DATABASE_URI marked for build time in Coolify and reachable from the build.
  • The build does not see the database → the plugin does not break the build (returns []), but pages render on demand (ƒ) and SEO falls back to the metadata-in-body problem. Make the database reachable from the build (same server/network, deployment.md §3a3).
  • generateStaticParams from lib/content covers only the pages collection (max 1000 per language); content collection entries and pages above the limit render on demand (ISR).
  • Routes that read the database (sitemap, manifest, llms.txt, health) have force-dynamic — they are not prerendered.

Test without a database: DATABASE_URI=mongodb://invalid-host:27017/x pnpm build → exit code 0.

4.4 Health check, rollback, backups, seed

  • Health check — Coolify → Health Checks on /api/health (healthRoute from lib/content = createHealthRoute pinging the pages collection: a database round-trip, 200/503, no-store), port 3000, a start period long enough for migrations. A rolling update keeps the old container when the new one is unhealthy (deployment.md §4.4).
  • Rollback — Coolify → Rollback → an earlier image (keep a few: image retention). It does not undo migrations → restore the pre-deploy backup if needed (deployment.md §4.5).
  • Backups — scheduled to S3/R2, Backup now before risky operations, restore via Import Backup; test restores (deployment.md §4.6).
  • Seed / one-off scripts in production — Coolify → Terminal in the app container: dry run → Backup now → real run (deployment.md §4.7, seeding.md).

4.5 After deploying

  • / redirects to the locale, the admin panel and login (2FA) work
  • the form sends (admin panel → Send test), media display (/api/media/file/… → 200 without login)
  • curl -A "Googlebot" URL | grep canonical — in <head>
  • /sitemap.xml, /robots.txt respond; favicon in <head>
  • security headers (securityheaders.com); www redirects to the canonical host
  • DNS records from deployment.md §6 checked with dig

4.6 Email — SMTP or Graph

Client on M365/Exchange → Graph (SMTP AUTH is often turned off). Own SMTP/Gmail → SMTP. The switch is in the admin panel (Site integrations → E-mail sending → Sending method). Graph, one-time: App registration in Azure, the Mail.Send application permission

  • Grant admin consent, the GRAPH_* variables. from.address always = GRAPH_SENDER (otherwise ErrorSendAsDenied); sender name from the admin panel; the visitor's address goes into replyTo. More: email.md.

5. COMPLIANCE (PL/EU) — CHECKLIST BEFORE HANDOVER

The boundary: we deliver the mechanism. The client or their lawyer writes the text of the policies and terms — we are not a law firm. Put this in the contract.

  • Policy pages created (privacy, cookies, terms if there are services/sales/accounts)
  • Roles assigned in System pages; content filled in (not a placeholder); noindex on policies
  • The banner shows on the first visit; "Reject" is as easy as "Accept"
  • Pixels (Meta, LinkedIn, TikTok) and Clarity do not load before consent (check Network). GA4/GTM load right away in Consent Mode v2 with default denied (advanced mode: no cookies, but with pings to Google) — if the client requires zero requests to Google before consent, this is currently not met (analytics.md)
  • CookieButton reopens the settings; cookies disappear after consent is withdrawn
  • Forms have a consent checkbox (required, enforced server-side) with a link to the policy
  • Data controller details in the global (policy + footer)
  • Everything in every language
  • Accessibility widget only when required (public bodies, some e-commerce — EAA)

6. UPDATING AN OLD PROJECT TO THE LATEST IAPL

One rule: when the plugin provides something the project has written by hand — delete the local version. Two versions = everything runs twice.

Do one item at a time, build, check. Order by importance:

# What Do Doc
1 Metadata in <body> htmlLimitedBots, remove <head> from the layout, revalidate, generateStaticParams, remove await searchParams seo.md, pages.md
2 middleware.ts / hand-written proxy createProxy (§2.6) i18n.md
3 manifest/sitemap/llms routes createManifestHandler, sitemap, createLlmsTxtRoute + force-dynamic; remove _status workarounds seo.md
4 ConsentWrapper with setTimeout delete — CookieBanner/CookieButton have their own mount guard consent.md
5 Language switcher with 404 LanguageSwitcher / switchLocalePath with getLocalizedSlugs i18n.md
6 Own Lexical parser RenderRichText richtext.md
7 Hand-written form logic, getSafeString useForm/useContactForm, resolveLocalized, honeypot forms.md
8 Hook with a ['pl','en'] list buildCrossLocaleFieldSync hooks.md
9 Hand-written noindex checkbox + hook buildNoindexField seo.md
10 Old slugs → 404 trackSlugHistoryHook + resolveRedirect in the catch-all hooks.md, content.md
11 No env validation instrumentation.ts + assertEnv env.md
12 Third-party scripts without consent ConsentScript / Analytics consent.md, analytics.md
13 No health check healthRoute from lib/content / createHealthRoute (§2.8) deployment.md
14 2FA crash "Cannot find module" inject plugin: payloadTotp security.md
14a workarounds from ≤ 1.8.13: a payloadTotp adapter cast to CollectionSlug, '@clocklimited/payload-2fa' in serverExternalPackages delete — plugin: payloadTotp directly, no entry in next.config security.md
15 ctaLabel/pdfUrl fields, monolithic sections refactor per AGENT.md §6.7 (with a data migration!) AGENT.md
15a buildR2Storage(['media']) without an adapter (since 1.8.1 an error when R2 env is set) pnpm add @payloadcms/storage-s3, buildR2Storage(['media'], { s3Storage }) storage.md
15b src/fields/link.ts, src/lib/links.ts in the project imports from the plugin, delete the copies (no database migration) links.md
15c createPageMetadata(...) in page.tsx generatePageMetadata(locale, slug) from lib/content — cache shared with the page component, fewer queries seo.md
15d no limits for oversized images / video in Media buildOptimizeUploadHook() + buildOptimizeUploadField(), field migration media.md
15e "Add Row" arrays, "Item 01" rows, cta1/cta2, PL labels in the admin panel labels + rowLabel() on arrays, slots → array (with a migration!), EN labels — AGENT.md §6.5a; after updating the plugin pnpm payload generate:importmap (buildLinksField uses RowLabel) links.md
15f public/sitemap.css + own route / app/sitemap.ts app/sitemap.xml/route.ts: export { sitemapRoute as GET } from '@/lib/content' + force-dynamic; delete public/sitemap.css and app/sitemap.ts seo.md
15g instrumentation.ts imports from the root (Edge/Turbopack crash: fileTypeFromFile) import { assertEnv, iaplEnvRules } from '@intecion/ipal-kit/env' + if (process.env.NEXT_RUNTIME !== 'nodejs') return; remove the dynamic await import env.md
15h <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(…) }}> <JsonLdGraph schemas={[…]} /> from @intecion/ipal-kit/rsc (escapes < — without it </script> in the admin panel = XSS) seo.md
15i own clamp() formulas in styles.css @import "@intecion/ipal-kit/fluid.css" + mapping in @theme (§2.5) —
15j the form front end sends fetch('/api/form-submissions') (from this version REST returns 403 for anonymous users) rewrite as a server action + submitForm (skill iapl-form) forms.md
15k Turnstile secret saved by code (updateGlobal in onInit / an action) or own verify without remoteip delete the workaround: secret in the admin panel or env TURNSTILE_SECRET_KEY; the plugin does not send remoteip and logs the rejection reason turnstile.md
15l a Turnstile outage blocked forms nothing in the project: on an error on our side the plugin accepts the submission and shows an alert in the admin panel; generate:importmap, Postgres: migrate:create turnstile.md
15m own plugin moving Notifications into a group; formOverrides/formSubmissionOverrides only for labels and the admin group delete — the plugin itself puts Form messages in the "Forms" group, and forms → the "Forms" group with labels (forms.adminGroup) forms.md
15n mail errors visible only in logs nothing in the project: mailAdapter() shows the send error on the dashboard and in Site integrations → E-mail sending; generate:importmap, Postgres: migrate:create email.md
16 Hard-coded 404 404 role in System pages + getNotFoundPage pages.md
16a privacyPolicy: { label: 'Polityka prywatności', … } in the layout delete the whole parameter; enter the text in Cookies → Privacy link label consent.md
17 AI/GEO (mandatory since 1.9.0) llms.txt + llms-full.txt, the /md/… route, markdownAlternate: true, prefersMarkdown in the proxy, /api/mcp, buildSummaryField, AI bots allowed — AGENT.md §0b content.md, seo.md, mcp.md
18 1.9.0 — TurnstileProvider siteKey from getSiteIntegrations(…).turnstileSiteKey getTurnstileConfig(payload).siteKey. Note: with both keys set submitForm requires a token — a form without the widget will be rejected turnstile.md
19 1.9.0 — twoFactor: { issuer } without plugin add plugin: payloadTotp (the fallback with a dynamic import was removed — startup fails with an error) security.md
20 1.9.0 — IP in the form action computed by hand from x-forwarded-for clientIp(await headers()) + IAPL_IP_HEADER in the production env forms.md
21 1.9.0 — media without R2 in production / no buildR2Storage wire buildR2Storage(['media'], { s3Storage }), set R2_* storage.md
22 1.9.1 — hand-written actions.ts / md route / no form seed createSubmitAction, createMarkdownRoute, seed from iapl-form (mail to the company + to the visitor) forms.md, content.md
23 1.9.1 — createProxy without markdown: true add it — otherwise /md/… redirects to /pl/md/… content.md
24 1.9.1 — page JSON-LD assembled by hand getPageJsonLd, buildNavigationJsonLd, sameAsUrls, formatOpeningHours seo.md
25 1.9.1 — consent: version, log, table Cookies → Policy version; consentLog: true + logEndpoint; <CookieBanner equalChoice>; scan + <CookieTable>; Postgres: migrate:create consent.md
26 1.9.1 — media: priority, no placeholders, images in next.config <Media> through mediaImageProps/videoProps, buildMediaPlaceholderHook, buildImagesConfig, buildUploadSecurityHeaders media.md, storage.md
27 1.9.1 — staging indexed IAPL_NOINDEX=1 in the staging env seo.md
28 1.9.2 — own FormRenderer (a copy of the engine on useForm) security: it passed the whole form document, including the Emails tab, to the browser (company addresses in the HTML). Block → <RenderForm form action locale texts classNames>, styling into formClasses.ts, delete FormRenderer.tsx; unusual form → useBuilderForm forms.md
29 1.9.2 — multi-step forms / choice lists built in code admin panel: the Step, Radio, Checkbox group, Date blocks; Form messages → next / back / stepOf; Postgres: migrate:create forms.md
30 1.9.2 — layout assembled by hand (ConsentProvider, TurnstileProvider, Analytics, JsonLdGraph, MediaPreconnect) <SiteProviders shell={await getSiteShell(locale)} …> — the same options (banner, analytics, jsonLd, logEndpoint) PROGRAMISTA §2.8
31 1.9.2 — catch-all page and not-found.tsx written by hand createPageRoute(content, {…}) / createNotFoundPage(content, {…}) from /rsc; revalidate stays a literal pages.md
32 1.9.2 — llms/md/mcp/health/indexnow/manifest routes with configuration in every file re-export from lib/content (llmsRoute, llmsFullRoute, markdownRoute, mcpGET/mcpPOST, healthRoute, indexNowKeyRoute, manifest); summaryField, mcp once in createContentHelpers PROGRAMISTA §2.7
33 1.9.2 — src/fields/sectionHeader.ts, sectionSettings.ts, lib/navigation.ts, hand-written resolveLinkHref in CMSLink buildSectionHeaderField, buildSectionSettingsField (same data shape — no migration), resolveNav, resolveLink from lib/content blocks.md, links.md
34 1.11.0 — a copy of publicForm, own field renderer with a variant / context RenderForm values or prepareBuilderForm + <BuilderForm values>; delete the copy forms.md
35 1.11.0 — extra "categories" relations next to links, links to entries as URLs buildLinkField({ relationTo: ['pages', 'categories'] }) (link data migration) links.md
36 1.11.0 — product / category JSON-LD assembled in the project, jsonLd: false pageJsonLd.entries + buildProductJsonLd, jsonLd back on in createPageRoute seo.md
37 1.11.0 — own RenderBlocks in the page route only for the first section's h1; storage in iaplEnvRules conditional on NODE_ENV; hand-written remotePatterns / dangerouslyAllowLocalIP for localhost isFirst from createPageRoute; iaplEnvRules({ storage: true }); buildImagesConfig() pages.md, env.md, storage.md
38 1.11.1 — revalidatePath wrapped in a process.env.NEXT_RUNTIME condition (seed / payload run failed) delete the condition — the hook skips revalidation outside Next itself; on purpose: context: { disableRevalidate: true } hooks.md
39 1.11.1 — focus guard around RenderForm (the page scrolled to the form on return) delete — BuilderForm moves focus only when the step changes forms.md
40 1.11.1 — own ThemeScript / theme switcher / useSyncExternalStore on data-theme <SiteProviders theme> (or <ThemeScript {...shell.theme}>), <ThemeSwitcher label={shell.theme.toggleLabel}>, useTheme; the same ipal-theme key — visitors' choice is kept. Postgres: migrate:create (system, themeToggleLabel) theme.md
41 1.11.1 — own anchors.ts / TableOfContents / heading converter with id extractHeadings, <TableOfContents> (/client), RenderRichText headingIds, buildTableOfContentsField() (same show/label shape — no data migration) richtext.md
42 1.11.1 — notFound caught in page.tsx to redirect to the homepage createPageRoute(…, { redirect, onMissing: 'redirectHome' }) pages.md
43 1.11.1 — <Media> sets the background color only for JPEG delete the condition — mediaImageProps does it itself (placeholderColor) media.md
44 1.11.1 — CmsLink['appearance'] replaced with an own type because the type depended on field order types per shape: CmsLink, CmsLinkPlain, CmsLinkNoLabel; pnpm generate:types and fix the imports links.md
45 1.11.1 — format description in a form field label / time as text the Placeholder field in the admin panel, the Time type; Postgres: migrate:create forms.md
46 1.12.3 — own cookie settings window / cookie list in the banner written in the project <CookieBanner settings="detailed"> (list from Cookies → Cookie list, captions: Detail labels); delete your own version; Postgres: migrate:create consent.md
47 1.13.0 — staff access, Search engines, seed scripts, workarounds around plugin globals without access: every logged-in account gets the staff features → access or globalOverrides / formOverrides / formSubmissionOverrides / collectionOverrides; with access: staff need editor/admin; Postgres: migrate:create; check settingsDepth, sitemap() throwing, 2FA slug, client IP; own seed code → @intecion/ipal-kit/seed; global hooks/access plugins → revalidatePath / globalOverrides CHANGELOG 1.13.0, AGENT.md §7.1, seo.md, seeding.md
48 1.14.0 — image lightbox — own image modal (useState(index) + div role="dialog"), glightbox / other lightbox library, thumbnails linking to the raw file in a new tab iapl({ lightbox: true }) + Postgres migrate:create; <SiteProviders lightbox>; <LightboxTrigger group image={lightboxImage(media, { size })}> around the thumbnail; delete the old dialog and pnpm remove glightbox; old label fields → Form messages → Image viewer lightbox.md → "Replacing a hand-made modal"
49 1.14.0 — import map, Node, Next, audit, cookie list, admin languages pnpm payload generate:importmap (FaviconCheck, RowLabel); Node 20.9+; next@^16.4.3 + sharp@^0.35.5 (Next ≤16.4.0 has two RCEs); pnpm audit --prod + dompurify / undici overrides on payload 3.90.x; hand-kept cookie list → cookieScanner (+ crawl, IAPL_COOKIE_SCAN_URL / IAPL_COOKIE_SCAN_TOKEN) + migrate:create; English-only admin → i18n.supportedLanguages; tests on validator strings → full sentences CHANGELOG 1.14.0, cookie-scanner.md, i18n.md, AGENT.md §4 items 11–12
50 1.14.1 — X-Powered-By: Next.js, Payload in responses, no CSP or a hand-written one withPayload(withSecurityConfig(nextConfig)); buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', …flags } }) + buildAdminCspHeaders on /admin/:path* + export const POST = createCspReportRoute(); after clean reports mode: 'enforce'; nonces (createProxy({ csp }) + <SiteProviders nonce>) only for dynamic sites security.md, CHANGELOG 1.14.1
51 1.14.2 — a new admin stuck on /admin/setup-totp?back=null (the page keeps redirecting to itself), or an own x-pathname rule on /admin added as a workaround pnpm payload generate:importmap (TotpRedirectProvider), commit importMap.js, redeploy; delete the workaround; own redirect rules → twoFactor.provider security.md → "The redirect to the 2FA screens", CHANGELOG
52 1.14.3 — editors open every Cookie review entry one by one to accept it with cookieScanner: pnpm payload generate:importmap (CookieApprovalView, CookieCrawlAlert), Postgres/SQLite migrate:create (change, needs_description); editors use Approve cookies (/admin/cookie-approval, linked from Privacy → Cookie review); old flow: cookieScanner: { approval: false } cookie-scanner.md, CHANGELOG 1.14.3
53 1.14.4 — cookie texts retyped in every language; three cookie entries in the admin navigation pnpm payload generate:importmap (CookieReviewTab, CookieSiteCheckTab); empty languages fill themselves (fillEmptyLocales: false to keep them empty); with cookieScanner one Cookies entry with tabs (cookieScanner: { adminLayout: 'separate' } for the old entries); Cookie banner is now called Cookies — update editor instructions; no migration consent.md, cookie-scanner.md, hooks.md, CHANGELOG 1.14.4
54 1.14.6 (1.14.5 never published) — /api/graphql answers 500; graphql-scalars high advisory; theme stored as ipal-theme; hand-written admin.meta for the panel preview Postgres: migrate:create for the title separator plus ${sql.raw(titleSeparatorSql())} after the first SET DATA TYPE text;, and the cookie storage type; graphql-scalars override (Node 22 recommended); THEME_STORAGE_KEY instead of 'ipal-theme'; titleSeparatorChar() for a raw settings.titleSeparator; remove hand-written panel admin.meta; pnpm exec iapl-skills (--external optional) CHANGELOG 1.14.6 + 1.14.5, seo.md, theme.md, white-label.md, consent.md
55 1.15.0 — a production seed runs everything; no design tokens / block library; no site check SEED_ONLY for production seeds (full seed refused, IAPL_SEED_ALLOW_FULL=1 with the owner's OK); optional tokens.css + the block library (block by block, migrate:create); CookieButton above the footer (avoid={false}); pnpm exec iapl-skills; pnpm exec iapl-doctor (--url); new sites with iapl create CHANGELOG 1.15.0, seeding.md, design-tokens.md, block-library.md, doctor.md, project-starter.md
56 1.15.1 — a seed in Coolify's Terminal ends with exit 0 and no output (it stopped before Payload started) guardSeedExit() first in every seed script, seed.summary() at the end; check echo $? after a seed; pnpm exec iapl-skills CHANGELOG 1.15.1, seeding.md
57 1.15.2 — iapl-doctor reports missing routes for a site whose pages live in app/(site) (not (frontend)), or a notFoundView.tsx nothing to change; remove the temporary layout-required silence; two candidates → layout.frontend in iapl-doctor.json; pnpm exec iapl-skills CHANGELOG 1.15.2, doctor.md
58 1.15.3 — iapl-audit / iapl-doctor report adminText() or { en, pl } panel labels as hardcoded Polish text pnpm exec iapl-skills; remove a temporary i18n-literals silence added for such labels; public text is still reported CHANGELOG 1.15.3, iapl-audit skill
59 1.15.4 — a seeded form / layout / global array shows only the last language (whole localized arrays) nothing to change in the seed; repair: SEED_UPDATE=1 locally, on production SEED_ONLY + SEED_UPDATE=1 + IAPL_SEED_ALLOW_PROD_UPDATE=1 after a backup; edited records and global arrays by hand CHANGELOG 1.15.4, seeding.md
60 1.15.5 — a seeded page with a required layout linking to a page or form fails validation ("… > Layout") nothing to change in the seed; run it again (dry run first); a missing $form / $page is now an error in the dry run too; a required link cycle: make one link optional CHANGELOG 1.15.5, seeding.md
61 1.16.0 — files on forms — a CV / drawing field built by hand (own upload collection, bucket, <input type="file"> posting to an own route), or "send the file by e-mail" asked for and refused forms: { attachments: true } + a File field (panel or seed) + one e-mail with a fixed recipient; Postgres/SQLite migrate:create; generate:types; formClasses keys file, help, fileList, fileItem, fileRemove; proxy body limit (nginx client_max_body_size 12m); Graph: Mail.ReadWrite limited to the forms mailbox, or SMTP settings, or ~2.8 MB; test e-mail with the 10 MB file; delete the hand-built upload path; pnpm exec iapl-skills CHANGELOG 1.16.0, forms.md "Files", email.md "Attachments", deployment.md "Form files"
62 1.16.1 — pnpm dev warns "Next.js 16.4.3 is affected by a known security vulnerability"; iapl-doctor next-min error below 16.4.5 (GHSA-mfr8-8qww-v76h) pnpm add [email protected] [email protected], rm -rf .next, build, commit the lockfile, redeploy on Coolify; pnpm exec iapl-skills; no option, migration or import map change CHANGELOG 1.16.1, AGENT.md §4 item 11
63 1.16.2 — pnpm audit --prod shows mongoose (critical, via @payloadcms/db-mongodb) or happy-dom (high, via @payloadcms/richtext-lexical); iapl-doctor transitive-min pnpm.overrides: "mongoose@>=8 <8.24.7": "~8.24.10" (MongoDB sites) and "happy-dom@<21.0.4": "^21.0.4"; pnpm install, build, commit the lockfile, redeploy on Coolify; pnpm exec iapl-skills; no migration CHANGELOG 1.16.2, AGENT.md §4 item 12
64 1.16.3 — the reference site and the starter run Payload 3.94.1; the site is still on 3.90–3.93, or node -v (locally or in the Coolify app's Terminal) is below 22.23.5 Recommended, not required (the plugin still accepts ^3.90.2). First make sure Node is 22.23.5 or later everywhere, Coolify included (Nixpacks picks the patch: check node -v, update Coolify if lower). Then every payload / @payloadcms/* 3.94.1 (in dependencies and pnpm.overrides), react / react-dom 19.3.1, "engines": { "node": ">=22.23.5 <23" }; overrides: keep dompurify and happy-dom, drop mongoose, undici and graphql-scalars; pnpm install, generate:types, generate:importmap, rm -rf .next, build, redeploy; Postgres/SQLite: migrate:create; pnpm exec iapl-skills CHANGELOG 1.16.3, AGENT.md §4 items 11–12, iapl-upgrade "Every upgrade — Payload"
65 1.16.4 — security — with 2FA on, a login with the password only gets 200 from /api/globals/site-integrations or /api/form-submissions; or the project has a second auth collection (customers) Upgrade and redeploy (no config change with one auth collection). With the owner: change the SMTP password and the Turnstile secret, review Site settings / Site integrations / each form's Emails tab for values nobody set. Second auth collection: admin: { user } in buildConfig, adminOrSelfIn('<slug>'), access.staffCollections only for a second STAFF collection. Every account must have 2FA set up (iapl-doctor --url → 0 without). Own endpoints: secondFactorPassed(req); own overrideAccess: false calls: user from payload.auth(). pnpm exec iapl-skills; no migration CHANGELOG 1.16.4, security.md "What the second factor covers", access.md "Who is staff"
66 1.16.4 — production PAYLOAD_SECRET shorter than 32 characters (the site would stop at assertEnv) Before deploying 1.16.4, check the length in Coolify (node -e 'console.log(process.env.PAYLOAD_SECRET.length)'). Shorter: a random 32+ character secret (logs everyone out, asks for 2FA again, breaks stored API keys), or iaplEnvRules({ secretMinLength: 0 }) for now CHANGELOG 1.16.4, deployment.md "PAYLOAD_SECRET — length and changing it"
67 1.16.5 — security — with 2FA on, /admin/verify-totp?back=https%3A%2F%2Fexample.com%2F sends the user to example.com after the code (and back=javascript:… runs script in the panel) Upgrade and, in ONE deploy, pnpm payload generate:importmap (adds @intecion/ipal-kit/admin#SafeTotpView), commit importMap.js, rm -rf .next, redeploy on Coolify — with the old map the 2FA screens have no code form and nobody can sign in (run pnpm exec iapl-doctor before deploying; the start log says so too); check: the link above ends on /admin. pnpm exec iapl-skills. No option, env or migration; off / own rule: twoFactor.safeBack CHANGELOG 1.16.5, security.md "The back link of the 2FA screens"
68 1.16.6 — 2FA setup required (not a routine patch: a new default that can lock accounts out) — an account that has not set 2FA up still reads data over the API with its password; or after the upgrade an account "can do nothing" / is blocked Before upgrading: iapl-doctor --url → accounts without 2FA set it up or are removed; one admin (better two) must have 2FA; deploy day agreed with the owner. Then, in ONE deploy: update, generate:types, generate:importmap (TwoFactorStatusField, TwoFactorAlert), Postgres/SQLite: migrate:create and the migration applied in the same deploy when the new container starts — prodMigrations or pnpm payload migrate && pnpm start, never a pre-deployment command (deployment.md §4.3) — (column totp_setup_from); without it every login answers 500, build, redeploy. Existing accounts get 72 h from the first start; blocked later → admin: account page → "Reopen setup". Password-login integrations: API key or requireSetup.exempt. pnpm exec iapl-skills CHANGELOG 1.16.6, security.md "Setup required"
69 1.16.7 — hardening (not a routine patch: stricter defaults) — an account with only the role user sees "Unauthorized" in the panel; or the API returns "smtpPassword":"********"; or a form with a File field is refused while Turnstile is misconfigured; or "The password must have at least 12 characters."; or "Enter the password again…" on the SMTP password; or 403 "Not allowed from this origin." on the 2FA code Update, generate:types, redeploy; no import map, schema or migration. Every slug in access.staffCollections must be an auth collection (otherwise Payload does not start: /api/health 503, the old container keeps serving). Set serverURL (a proxy that rewrites Host otherwise blocks the 2FA code; the log names the origin). Read the start log (N account(s) … cannot open the admin panel) and give panel users editor. Own code that read the two secrets over the API → Local API on the server. TURNSTILE_SECRET_KEY is deprecated: with the owner move the key into the panel. Own staff collection without rules: an admin (update: or the account itself; roles only by an admin; read by staff only) where the roles are the plugin's, accounts of that collection where they are the project's own — write that collection's own rules. Existing short passwords keep working. Switches: accounts, secrets, forms.turnstileOnConfigError, twoFactor.sameOrigin, dashboardAlerts. pnpm exec iapl-skills CHANGELOG 1.16.7, access.md "Account rules", security.md "Stored secrets", turnstile.md
70 1.16.7 — next build --webpack: 'server-only' cannot be imported from a Client Component module, from a 'use client' file that imports isAdmin, isEditor or hasMinimumRole Import them from @intecion/ipal-kit/client in client components, keep the second argument (isAdmin(user, config)); import type may stay on the main entry CHANGELOG 1.16.7, access.md
71 1.17.0 — security (prepared as 1.16.8, released in 1.17.0) — a site built with Turbopack (next build without --webpack) serves /_next/static/media/package.<hash>.json; or the project has a staff collection of its own without access rules; or a plugin listed after iapl copies a staff collection or sets admin.user; or the start log says No staff account holds the role "admin", so NOBODY can … Update, pnpm exec iapl-skills, rm -rf .next, rebuild; no option, schema, migration or import map. Turbopack: find .next/static -name 'package*.json' empty, purge a CDN. Own staff collection: a roles list that can hold editor / admin → only an admin manages its accounts (write own rules otherwise; one account must hold admin); a single select with only user / editor / admin → its accounts manage each other again (own rules if your code goes by the value). A copy: access.update: adminOrSelfIn('copy'), or custom.ipal.accountRules: false CHANGELOG 1.17.0 "Security", access.md "Account rules"
72 1.17.0 — the plugin is called IAPL — you see iapl(), iapl-doctor, IAPL_IP_HEADER, iapl-doctor.json, [iapl] in docs and logs and wonder whether the project must change No. Every old name works through 1.x (ipalKit, ipal-* commands, IPAL_* env, ipal-doctor.json, ipal-audit-skip, the old pointer block); the package is still @intecion/ipal-kit. Run pnpm exec iapl-skills (or the project's ipal:skills script) and commit; change a log filter on [ipal] to [iapl]. Rename the rest only when the owner asks (iapl-upgrade "→ 1.17.0", AGENT.md "Names: IAPL and ipal-kit"). Never set storageNames: 'iapl' on an existing site
73 1.17.0 — e-mail: the Intecion mail service is the default transport — a site with no SMTP server in the panel and no GRAPH_* starts sending through the service after the upgrade (an outbound call with its host; a new public route POST /api/iapl/mail-relay/confirm; mail from [email protected]); a Graph site warns at start Nothing to run (no schema, migration or import-map change). SMTP site: nothing. Graph site: nothing now — deprecated, move when the owner says. Site with neither: agree it with the owner; serverURL = the public address, "Sender address" filled in, the host listed by Intecion; or iapl({ mail: { relay: false } }) to keep the old behaviour iapl-upgrade "→ 1.17.0, e-mail", AGENT.md §7.2, email.md
74 1.17.0 — Postgres — a Postgres site with many form submissions or "forgot password" requests at the same moment stopped answering (every page waited); after the update transactionWatchState shows a reserve, form and account mail arrive a moment after the save Nothing to run. Default: a fifth of the pool (at least 2) kept free of transactions; form, "forgot password" and "verify" mail sent right after the commit; shorter SMTP time-outs. The old way: connectionReserve: false, forms: { emailsInTransaction: true }, mail: { accountMailAfterCommit: false }. An own e-mail adapter calls sendAccountMailAfterCommit first. MongoDB / SQLite: no change CHANGELOG 1.17.0 "Fixed — Postgres", deployment.md §4.3a, forms.md "When e-mails go out"
75 1.17.0 — e-mail: launch day and copies — a site moves from <name>.dev.netscale.pl to its real domain (the real domain must send with no click); or production's database is copied to a development or staging address (it must not mail real people); or the start stops with "developmentHosts must be an array of host patterns" Nothing to run on launch day. A development address matching iapl({ developmentHosts }) (built in *.dev.netscale.pl) or a site with IAPL_NOINDEX=1 that holds another host's connection sends nothing until an admin presses "Connect again". Other staging hosts: add their pattern to developmentHosts (an array of non-empty patterns; [] = none). Production never keeps IAPL_NOINDEX iapl-upgrade "→ 1.17.0, e-mail", email.md "Staging, copies and several hosts"
76 1.17.0 — public pages: Chrome requests the first page of a visit twice — curl -sI <site>/pl shows Critical-CH: Sec-CH-Prefers-Color-Scheme (Payload's withPayload adds it for every path; only the admin reads the hint); Lighthouse lists the same URL twice under redirects next.config.ts: withSecurityConfig(withPayload(nextConfig)) — the plugin's wrapper OUTSIDE (was inside). Another panel address: { adminClientHints: { route } }; keep the old behaviour: { adminClientHints: false }. Without the edit nothing changes iapl-upgrade "→ 1.17.0, the public pages' first request", security.md "Client hints"

After updating the package: pnpm exec iapl-skills (new skill versions), pnpm payload generate:importmap, rm -rf .next, restart dev, grep for the new symbol in node_modules/@intecion/ipal-kit/dist.


7. TROUBLESHOOTING

Symptom Cause / fix
Empty SEO tab, no Forms collection @payloadcms/* version mismatch — pnpm.overrides
PayloadComponent not found in importMap pnpm payload generate:importmap
Cannot destructure property 'config' duplicate @payloadcms/ui in the plugin — ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms/ui
Cannot find module '@clocklimited/payload-2fa' inject plugin: payloadTotp in twoFactor (serverExternalPackages does not help)
TS2322 on plugin: payloadTotp / iapl-skills: command not found IAPL ≤ 1.8.13 — update
[iapl] R2 storage: … adapter was not injected pnpm add @payloadcms/storage-s3 + buildR2Storage(['media'], { s3Storage })
Images 403 for visitors (/api/media/file/…) the Media collection has no public read — access: { read: () => true } (storage.md)
R2_PUBLIC_URL is required but missing in production media through the app — make the rule optional (env.md)
New deploy never goes live / old version keeps serving the health check fails (migration error, database unreachable) — Coolify deployment log (deployment.md §4.4)
Banner without styles no Tailwind or no @source for the plugin
/admin, /_next → 500 the proxy matcher is not an inline literal
slug.join is not a function [slug] instead of [[...slug]]
/pl → 404 Homepage not assigned in System pages
/en/* → 404, /pl/* works empty title/slug in EN
Missing <html> and <body> root layout deleted, and [locale]/layout.tsx does not have them
Routes ƒ despite generateStaticParams the build does not see the database (§4.3)
Build fails on ENOTFOUND / Mongoose a route that reads the database without force-dynamic
Emails are not sent no email: mailAdapter() or an empty transport in the admin panel
Plugin change not visible dev not restarted / old version in node_modules / rm -rf .next
Admin panel change not visible on the front end Save was not clicked, or ISR — buildRevalidateHook
Old email sender name mail client cache — check the raw headers

"Good code, wrong behavior" — in this order: restart dev (Payload builds adapters at startup) → save in the admin panel → duplicate dependency → importmap → cache.


8. IAPL DEVELOPMENT AND PUBLISHING

8.1 Change chain

Pre-release checks are the tests in test/ (also run by prepublishOnly): docsConsistency.test.ts (every import in the docs exists in the given entry point / in lib/content, every public export is described in the docs) and exports.test.ts (@intecion/ipal-kit/… paths from the docs exist in exports). There is no ipal-release skill with check-exports/check-deps in the repo. The version number always comes from a human.

A change does not work in a project until it has passed every stage:

src → commit → version → publish (runs clean + build + tests itself) → pnpm add in the project → restart
cd ~/payload-cms/ipal-kit
grep -c "<symbol>" src/<path>                    # >0 — the change is saved
# docs/: API/behavior change → update the module file IN THE SAME commit
pnpm clean && pnpm build
grep -c "<symbol>" dist/<path>                   # >0 — the build picked it up (export in index.ts!)
# docs/CHANGELOG.md: new ## <version> section at the top (keep at least the last 20 versions)
git add -A && git commit -m "description"        # BEFORE version (dist/ is ignored anyway)
npm version <version>                            # a human gives the number; minor = new API, major = breaking
npm publish                                      # registry from publishConfig (Gitea), no --registry
git push && git push --tags

cd ~/<project>
pnpm add @intecion/ipal-kit@<version>
grep -c "<symbol>" node_modules/@intecion/ipal-kit/dist/<path>   # >0
pnpm dev                                         # restart

Grep for a single symbol, not a phrase — key order in an object gives a false 0. Common traps: npm version before the commit (dirty repo), a missing export in src/index.ts (is not a function in the project), pnpm add while dev is running.

dist/ is not in git (.gitignore). prepublishOnly runs pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate before every npm publish, so you cannot release a stale dist, a version with red tests or a starter that does not produce a working site (docs/project-starter.md; pnpm clean && pnpm build above is only a grep check before the commit). prepare (pnpm build) builds the package on install from git and on pnpm install in the repo. pnpm e2e:built is not in prepublishOnly either (it needs the reference site's .env and database): it is a required step of §8.1. typecheck and lint are not in prepublishOnly — before a commit: pnpm typecheck && pnpm lint && pnpm test:int (CI in .gitea/workflows/ci.yml runs typecheck, lint, test:int and build on push and PR).

8.1b The reference site (reference/) — part of every release

reference/ is one complete client site on the plugin ("Example Studio", made up; not in the npm package). Agents copy from it (docs/agent/reference-site/INDEX.md, shipped) and the project starter is generated from it. A release is not done until the reference site uses it. Before npm version:

  • Everything new or changed in this release is used in reference/ — a new option set, a route wired, a block or variant shown (the Blocks page picks up new blocks and variants from blockLibraryManifest by itself).
  • reference/ upgraded the way iapl-upgrade tells client projects; the upgrade notes are tried here first.
  • Local run green: pnpm build (plugin) → pnpm --dir reference install --ignore-workspace (refreshes the injected copy) → in reference/: pnpm generate:types && pnpm generate:importmap (no diff), pnpm typecheck, pnpm seed on a throwaway MongoDB, pnpm build, ALLOW_LOCAL_MEDIA=1 PORT=3100 pnpm start, pnpm test:e2e (Playwright's global setup runs e2e/create-test-admin.ts first: test admins reset, stored 2FA attempt counts cleared, so the result does not depend on what ran before; the fresh-site spec on an EMPTY database: E2E_SKIP_ADMIN_SETUP=1).
  • pnpm legacy:site green — required through 1.x. The reference site as it was at v1.16.7 (the last release before the rename to IAPL: ipalKit(), ipal-tokens, ipal-doctor.json, ipal-* skills), unpacked and installed against this build without one edit: the old commands run, the doctor reports no error, the committed import map and tokens.css are still current, tsc passes, and it builds with webpack and with Turbopack. This is the proof that an existing site upgrades with no change (scripts/legacy-site-check.mjs; DATABASE_URI = a reachable local MongoDB, an empty one is enough). With it: test/legacyNames.test.ts (every old name) and test/legacyNameForms.test.ts (no new name is born with the old spelling).
  • pnpm e2e:built green — required, no release without it. It builds the reference site with webpack AND with Turbopack (with the late-staff fixture, E2E_LATE_STAFF=1) and runs, on each built site: the account rules of staff collections the project or a later plugin adds (e2e/late-staff.spec.ts), "no package manifest among the public files", and "client hints" (Payload's colour-scheme headers on the admin only; Chrome requests a public page once). Unit tests run unminified code and cannot see what a bundle renames or publishes — two defects of the 1.16.7 review lived only in a built site. Needs reference/.env (local seeded MongoDB, E2E_* test admin); port from E2E_BASE_URL. Afterwards git status is clean (the command puts the reference site's generated types and import map back, also when it fails); rebuild the reference site without the fixture (pnpm build there) before other checks.
  • pnpm version <x.y.z> or npm version <x.y.z> --no-git-tag-version writes the version into src/version.ts as well (the version script; by hand: node scripts/write-version.mjs). Not pnpm --ignore-workspace version …: that runs the version script itself with the arguments and fails. test/version.test.ts fails when the constant differs from package.json.
  • pnpm reference:index → docs/agent/reference-site/INDEX.md committed (test/referenceIndex.test.ts fails otherwise; a new file in reference/ needs its line in scripts/reference-index.mjs → DESCRIPTIONS).
  • CI job reference green (.gitea/workflows/ci.yml), the starter check included once iapl create ships.
  • Tag v<version> pushed — the index links to reference/ at that tag, and git diff v<old> v<new> -- reference/ is the upgrade guide for projects.

The site uses the plugin as file:.. with dependenciesMeta.injected, so the plugin's peers (Payload, React, @payloadcms/ui) resolve from the site — a plain link:.. loads two copies of @payloadcms/ui and the admin crashes.

8.1a Plugin tests

test/ (outside src, not shipped in dist), vitest: pnpm test:int (once), pnpm test:watch.

Kind Where For what
unit test/<module>.test.ts pure functions: paths, metadata, robots, CSP, parsers (opening hours, Markdown), validation
with a fake Payload test/helpers.ts → fakePayload() logic on the Local API without a database: submitForm, Turnstile, MCP, IndexNow
integration test/integration.test.ts, test/drafts.test.ts — real Payload + in-memory SQLite access, hooks, field schema, drafts, globals — everything the fake cannot reproduce
package contract test/exports.test.ts every @intecion/ipal-kit/… path from the docs exists in exports
docs ↔ code test/docsConsistency.test.ts names imported in the docs exist in the entry points / lib/content; every public export is described in the docs
e2e pnpm test:e2e (Playwright) pnpm test = test:int + test:e2e
a site from before the rename pnpm legacy:site (scripts/legacy-site-check.mjs); test/legacyNames.test.ts, test/legacyNameForms.test.ts the v1.16.7 reference site, unedited, on this build: old commands, doctor, import map, types, both bundlers; every old name still works; no new ipal name
built site, both bundlers pnpm e2e:built (scripts/e2e-built.mjs, the reference site) what only a production bundle shows: nothing decided by a function's name, nothing private among the public files (§8.1)

Rules: every fixed bug = a regression test (check that it fails on the old code); no network (vi.spyOn(globalThis, 'fetch')); env through vi.stubEnv + unstubAllEnvs; server-only mocked (vi.mock('server-only', () => ({}))); a test for a behavior change visible to projects → an entry in docs/CHANGELOG.md. Test the skill scripts (audit.sh, seo-check.mjs, cookie-scan.mjs) on a fake site/project in a scratchpad: an empty project (only errors) and a complete one (0 errors). CI (.gitea/workflows/ci.yml) runs typecheck, lint, tests and build on every push.

8.2 Plugin package.json

  • "files": ["dist", "docs", "bin", "src/modules/block-library"] — the docs and the iapl-skills command ship in the package (the block-library source is what iapl-blocks eject copies); agents in projects read node_modules/@intecion/ipal-kit/docs/agent/AGENT.md. Without docs they have nothing.
  • One exports block, all paths to ./dist/ (not ./src/).
  • payload, @payloadcms/*, next, react → peerDependencies (in dependencies = a second copy = hooks without context). react-dom is not listed (it comes with next). Optional peers (peerDependenciesMeta): @clocklimited/payload-2fa, @payloadcms/storage-s3. dependencies hold only: lucide-react, nodemailer, server-only, slugify.
  • publishConfig.registry = the Gitea registry — npm publish will not reach the public npm.
  • No self-reference (never pnpm add in the plugin directory).
  • The plugin never imports next/server, next/cache, @payload-config or optional packages directly — the project injects them (the NextResponse, revalidatePath, payloadTotp, s3Storage pattern). Optional package = optional peerDependency + a minimal-shape type in the plugin, zero imports.
  • Import from next/* in a plugin client component: with the extension ('next/navigation.js') — next has no exports field, otherwise NodeNext cannot find it.
grep -c '"exports"' package.json            # 1
grep -c "git+https.*IAPL" package.json  # 0
grep '"import"' package.json | head -1      # ./dist/

8.3 Publishing token

Gitea → Settings → Applications → a token with write:package, in the global .npmrc (~/.npmrc, Windows %USERPROFILE%\.npmrc):

//git.intecion.net/api/packages/IntecionSoftware/npm/:_authToken=${GITEA_TOKEN}

8.4 Verification after publishing

pnpm store prune
pnpm add @intecion/ipal-kit
node -e "console.log(require.resolve('@intecion/ipal-kit/next/middleware'))"   # → dist/…
ls node_modules/@intecion/ipal-kit/docs/agent/AGENT.md
Symptom Cause
Cannot find module …/src/…ts exports points to src
"Module not found" although the file exists two exports blocks
ENOENT …IAPL.tgz self-reference in dependencies
old code despite reinstalling version not bumped; pnpm store prune + rm -rf .next node_modules/@intecion

Versions: 1.x = Payload 3. Moving to Payload 4 → IAPL 2.0.


9. GIT AND GITEA (git.intecion.net)

9.1 Access (once)

HTTPS + token: Gitea → Settings → Applications → a write:repository token. On clone/push: your Gitea login, and the token as the password (the account password does not work). To remember it: macOS git config --global credential.helper osxkeychain, Windows … manager, Linux … 'cache --timeout=3600'.

SSH: ssh-keygen -t ed25519 -C "[email protected]", public key to Gitea → Settings → SSH / GPG Keys, test with ssh -T -p 22222 [email protected].

git clone https://git.intecion.net/IntecionSoftware/<project>.git
git clone ssh://[email protected]:22222/IntecionSoftware/<project>.git

9.2 Daily

git pull                                   # before work and before push
git checkout -b <feature>                  # work on a branch
git add . && git commit -m "what and why"
git push -u origin <feature>               # then a Pull Request to main in Gitea

Never git push --force on main (only on your own branch).

9.3 Several projects

Each project is a separate directory and repo (~/projects/client-a, ~/projects/ipal-kit). Git works on the directory you are in — after cd always run git status and git remote -v before you push anything.

9.4 Errors

Message Fix
Permission denied (publickey) key not added in Gitea or wrong port (-p 22222)
Unauthorized / password prompt over and over use the token instead of the password; scope write:repository
non-fast-forward, "tip … is behind" git pull, resolve conflicts, git push
repository not found wrong address or no access to the repo
404 on pnpm add @intecion/… no @intecion:registry line in the project's .npmrc