# seeding — content seeds that never overwrite production > **VERY IMPORTANT — the first rule of seeding.** Once a site is live, **never run a full seed again**: the owner's > edits on the live site must survive. Every later change targets **named records only** — specific pages, > globals, forms or fields — listed in the seed (`only: [...]` / `SEED_ONLY="pages:kontakt,global:header"`). > Never re-seed everything, not even in create-only mode, without the owner's explicit OK. `createSeeder` > refuses a run with no record list against a production or non-local database unless `IPAL_SEED_ALLOW_FULL=1` > (set it only after that OK). A seed is a script that puts content into the database: pages, forms, globals. ipal-kit ships two templates. Copy them into the project and fill them from the brief: | Template | Copy to | Seeds | |---|---|---| | `docs/agent/skills/ipal-site/resources/seed-content.template.ts` | `scripts/seed-content.ts` | pages (or another collection with a slug) and globals, every language | | `docs/agent/skills/ipal-form/resources/seed-form.template.ts` | `scripts/seed-form-.ts` | one form: fields, confirmation, both e-mails, every language | Both are thin scripts over the seed helper `createSeeder` from `@intecion/ipal-kit/seed` ([The seed helper](#the-seed-helper)), which implements every rule below. A seed you write yourself should use it too; if it does not, it must follow the rules by hand. ## Rules 1. **Create-only and idempotent.** A seed creates what is missing and skips what exists. Running it twice changes nothing the second time. 2. **Match by a natural key, never by ID.** IDs differ between databases. | Record | Key | |---|---| | page, content entry | the slug in the default locale | | form | the form title | | global | the global itself (there is only one) | 3. **Never delete.** No `payload.delete`, no "clean up first". A record that should go away is removed by a person in the panel. 4. **After launch, named records only.** Before launch the seed may build the whole site. After launch a seed lists exactly the records it may touch (`only`, `SEED_ONLY`) — everything else is reported as `skip (not listed)` and never read for writing. A full run against a live database needs the owner's explicit OK and `IPAL_SEED_ALLOW_FULL=1`. Record the launch date in `AGENTS.md` → "Project decisions". 5. **Never seed users, passwords or secrets.** SMTP, Turnstile, API keys and tokens stay in the panel or in env vars. The first admin is created on the first-user screen. 6. **Globals: fill only empty fields.** A field that already has content is kept. 7. **Media: leave upload fields empty or reference existing uploads by ID.** Never upload files in a production seed. The editor adds images. 8. **Write each locale separately, with `fallbackLocale: false`.** See [Locales](#locales). 9. **Pass the context flags** the plugin reads. See [Context flags](#context-flags). ## Running a seed | Command | What it does | |---|---| | `SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts` | no writes; prints the plan | | `pnpm payload run scripts/seed-content.ts` | creates what is missing, never overwrites | | `SEED_UPDATE=1 pnpm payload run scripts/seed-content.ts` | also updates records nobody edited since seeding | | `SEED_ONLY="pages:kontakt,global:header" pnpm payload run scripts/seed-content.ts` | after launch: only the listed records (`collection:slug`, `forms:`, `global:<slug>`, `collection:*`) | `--dry-run` after the script path does the same as `SEED_DRY_RUN=1`, for example with a package script: `"seed:content": "payload run scripts/seed-content.ts"` → `pnpm seed:content --dry-run`. Every run prints one line per record and a summary: | Status | Meaning | |---|---| | `create` | the record is missing; the seed creates it (for a global: fills its empty fields) | | `skip (exists)` | the record exists; nothing changes | | `update` | `SEED_UPDATE=1` and nobody edited the record since seeding; the seed overwrites the seeded fields | | `skip (edited)` | `SEED_UPDATE=1`, but an editor changed the record; it is kept (the line says why) | | `skip (not listed)` | the record is not on the run's list (`only` / `SEED_ONLY`); it is not touched | | `error` | the write failed; the script exits with code 1 | The summary table counts `created`, `skipped`, `updated`, `skipped-edited`, `not listed` and `errors`. ## Before you run a seed on production 2. **Dry run.** Run the seed with `SEED_DRY_RUN=1` and read every line. Expect `create` and `skip (exists)`. 3. **Test on a copy.** Run it on staging or on a local copy of the production database first. 4. **Back up the database.** - Coolify: the database resource → **Backups** → **Backup now** ([deployment.md §4.6](./deployment.md)). - Postgres by hand: `pg_dump -Fc "$DATABASE_URI" > before-seed.dump` - MongoDB by hand: `mongodump --uri="$DATABASE_URI" --archive=before-seed.archive` 5. **Run it for real.** Check the panel and the site. **Restore, if something went wrong:** - Coolify: the database resource → **Import Backup** → pick the backup → check the restore command → start. Stop writes from the app first. - Postgres by hand: `pg_restore --clean --if-exists --no-owner -d "$DATABASE_URI" before-seed.dump` - MongoDB by hand: `mongorestore --uri="$DATABASE_URI" --archive=before-seed.archive --drop` ## Updates on production A seed may update a record on production only when **both** are true: - the seed created it, and - nobody edited it since. Anything an editor changed is always skipped and reported as `skip (edited)`. `SEED_UPDATE=1` is **refused** when `NODE_ENV=production` or when the database is not local. It runs only when `IPAL_SEED_ALLOW_PROD_UPDATE=1` is also set. The refusal message tells you to back up first. A database counts as local when `DATABASE_URI` is a SQLite file (`file:…`), a Unix socket, or a URL whose host is `localhost`, `127.0.0.1` or `::1`. Everything else is not local, including Docker service names (Coolify) and `mongodb+srv://`. ### How a seed tells "edited since seeding" | Method | How it works | Status | |---|---|---| | **Timestamps** | `updatedAt` is at most `SEED_UNTOUCHED_SECONDS` (default 120) after `createdAt`. The seed's own writes happen in that window; any later save, by an editor or by a seed update, moves `updatedAt`. | **primary** — works in every project, no schema change | | **Seed hash** | A hidden text field (default name `seedHash`) stores a hash of the values the seed wrote. On the next run the seed hashes the current values at the same keys. A different hash = an editor changed something. | optional — needs a field in the collection or global | Timestamps are simple and safe, but they allow **one** update per record: after a seeded update `updatedAt` moves on, so the next run reports `skip (edited)`. When you need repeated updates, add the hash field. The seed helper uses it automatically when the collection or global has a top-level field with that name; the stored hash then decides instead of the timestamps. ```ts // a collection (pages) or a global — for forms use ipalKit({ forms: { formOverrides: { fields } } }) { name: 'seedHash', type: 'text', admin: { hidden: true } } ``` Postgres: adding the field needs a migration (`pnpm payload migrate:create`). Payload sets `updatedAt` on every save, so a seed cannot "reset" it. A hash that differs only because of storage formatting counts as edited — the safe side. ## Locales Write the default locale first. It creates the structure: blocks and array rows. Then write every other locale onto the **same row ids**. New row ids would wipe the other languages' texts. Read and write every non-default locale with `fallbackLocale: false`. With `localization.fallback: true`, Payload fills missing values from the fallback locale. An update in locale X without `fallbackLocale: false` saves those fallback values as the X translation: the Polish text ends up in the English version. See also [i18n.md](./i18n.md). ## Context flags Pass them in `context` on every `create`, `update` and `updateGlobal` (`createSeeder` does it on every write): | Flag | Read by | Effect | |---|---|---| | `disableRevalidate: true` | `buildRevalidateHook` ([hooks.md](./hooks.md)) | no `revalidatePath` for seeded records (outside Next the hook already does nothing) | | `ipalSkipIndexNow: true` | the IndexNow hook (`indexNow` option, [seo.md](./seo.md)) | no IndexNow ping for seeded, often placeholder, content | | `ipalSeed: true` | nothing in the plugin | lets the project's own hooks recognise a seed | ## Running a seed on Coolify 1. Coolify → the application → **Terminal** → the app container ([deployment.md §4.7](./deployment.md)). 2. Dry run with the record list: `SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts` — the plan must name only the records the owner asked for. 3. Back up the database (**Backup now**). 4. The real run, without `SEED_DRY_RUN`. 5. Check the exit code (`echo $?`): `0` with the summary means done. A run that stops early prints `[seed] ended before …` and exits `1` (`guardSeedExit`, below) — run it again; nothing after that point was written. The seed script and its dependencies must be in the image. Env vars (`DATABASE_URI`, `PAYLOAD_SECRET`, …) must be available at runtime, not only at build time. The container already has `NODE_ENV=production`, so `SEED_UPDATE=1` is refused there unless you add `IPAL_SEED_ALLOW_PROD_UPDATE=1`, and a run without `SEED_ONLY` is refused unless you add `IPAL_SEED_ALLOW_FULL=1` (only with the owner's explicit OK). ## Seeds or migrations? | Change | Tool | |---|---| | Schema: new field, new collection, changed type | Payload migration: `pnpm payload migrate:create`, runs on deploy ([deployment.md §4.3](./deployment.md)) | | Data fix that must run exactly once on every database | Payload migration | | Field rename or move that must keep content | the **ipal-migrate-fields** skill | | Content: pages, forms, globals from a brief | seed | A seed never changes the schema. A migration never fills editorial content from a brief. ## The seed helper `@intecion/ipal-kit/seed` is a server-only entry for seed scripts (plain Node via `pnpm payload run`). Never import it from client code, the Payload config or a route. It does not import `server-only`, because that package throws outside a bundled server. ```ts // scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts import config from '@payload-config' import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed' import { getPayload } from 'payload' guardSeedExit() // first — an early exit becomes exit 1 with the reason, never a silent 0 const seed = createSeeder(await getPayload({ config })) await seed.upsertBySlug('pages', [ { title: { pl: 'Start', en: 'Home' }, slug: { pl: 'start', en: 'home' }, layout: [/* … { $page: 'kontakt' } … */] }, { title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' } }, ]) await seed.upsertBy('forms', { title: 'Contact form' }, { title: 'Contact form', fields: [/* … */] }) await seed.fillGlobal('header', { phone: '[TO FILL: phone]' }) process.exit(seed.summary().errors ? 1 : 0) ``` **Seed values.** Write each value once, every language side by side. An object whose keys are all locale codes is one value per locale (`{ pl: 'Kontakt', en: 'Contact' }`); anything else is the same in every locale. A locale missing from such an object is left untouched in that locale. This works at any level: a text (`label: { pl, en }`) or a whole array, layout or group (`fields: { pl: [...], en: [...] }`). Rows of a field that is not localized are shared by every language — the helper reuses their ids, so give each language the same rows in the same order (its texts differ; non-localized values such as an option's `value` come from the last language written). A field with `localized: true` keeps its own rows per language. `{ $page: 'kontakt' }` becomes the ID of the page whose default-locale slug is `kontakt`; `{ $form: 'Contact form' }` becomes the ID of the form with that title (seed the form first). A missing form is an error for that record, never an empty relation. **References and required fields.** A new record is created complete, so a required field (a `layout` whose block links to a page or form) passes validation: - a reference to a record that exists — or was created earlier in the run — becomes its ID in the first write; - a `{ $page }` to a page created later **in the same `upsertBySlug` call** is filled in the second pass; when the field that holds it is required, the record waits until that page exists. Pages that link to each other belong in one call (an array); - required links in a cycle (A needs B, B needs A) and a reference to a page or form that does not exist and is not planned are an **error** for those records, and nothing is written for them. Make one of the links optional, or seed one of the pages first; - the dry run reports the same outcome. A form planned earlier in the same dry run counts as existing. Only a required cycle shows up first in the real run, because the dry run does not validate fields. Ready pages made of library blocks: `pageTemplates` in [block-library.md](./block-library.md#page-templates). | Method | What it does | |---|---| | `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (references to existing records resolved, links to pages later in the call filled in pass 2; a required one waits for its page), then every record gets its full content, so pages can link to each other in any order. Unknown targets and required cycles: error, nothing written | | `upsertBy(collection, key, data)` | matches by other natural keys, e.g. `{ title: 'Contact form' }` (all keys must match, default locale) | | `fillGlobal(slug, data)` | fills only the global's empty fields (the default locale decides). A choice — select, radio, checkbox, number, date — still at the field's `defaultValue` counts as empty (Payload stores defaults on the first save, so `defaultTheme: 'system'` can be seeded over `light`); text is never treated so, even when it equals a default. A field that already holds exactly the seeded value is not written (`skip (exists)`), so re-running a seed of defaults changes nothing. With `update` and an untouched global: every seeded field | | `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, errors }` | Each method prints one line per record (see [Running a seed](#running-a-seed)) and returns `{ status, label, id, note }`. A failed write is reported as `error` and the run goes on; exit with code 1 when `summary().errors` is not 0. `createSeeder` itself throws when the production guard refuses the run. ### A run that ends early fails loudly — `guardSeedExit()` `payload run` starts the CLI with `void start()` and then imports the script. When the script's top-level `await getPayload()` (or a later await) is left with nothing that keeps Node's event loop alive, Node simply exits: **code 0, no output** — in Coolify's Terminal that looks exactly like a successful seed. Call `guardSeedExit()` first in every seed script (the templates and the reference site do): | The run | Exit | What you see | |---|---|---| | ends before Payload initialized | 1 | `[seed] ended before Payload initialized — the run stopped early …` | | ends after `createSeeder` but before `summary()` | 1 | `[seed] ended before the seed finished — …` | | finishes: `summary()`, then `process.exit(errors ? 1 : 0)` (or ends naturally after the summary, e.g. a dry run) | 0 / 1 | the summary, as before | | a write fails | 1 | the `error` lines and the summary, as before | | the production guard refuses (`full seed refused`, `update refused`) or the script throws | 1 | the error, as before (`payload run` prints it) | `createSeeder` marks the run initialized and `summary()` marks it finished, so the guard needs nothing else. `guardSeedExit({ label: '[seed-form]', log, process })` — label of the message, where it goes (default stderr), and the process (tests). `dispose()` stops watching. Check: `pnpm seed` with a reachable database prints the summary as before; an interrupted run prints the line above and `echo $?` shows `1`. On a collection with drafts the helper reads the latest draft, both to match records and to tell whether an editor changed them. ### Building blocks | Export | Use | |---|---| | `guardSeedExit({ label, log, process })` | the early-exit guard above → `{ initialized, finished, dispose, state }`; `activeSeedExitGuard()` returns the current one (`createSeeder` and `summary()` report to it) | | `isLocalDatabase(url, { localHosts })` | the "local database" test of [Updates on production](#updates-on-production) | | `writeLocales(payload, target, data, { context, draft })` | writes seed values to an existing record (`{ collection, id }` or `{ global }`) in every locale: the default locale first, then the others with `fallbackLocale: false` onto the same row ids | | `seedHash(value)` | the hash stored in the hash field: key order, row ids and `null`s don't change it | | `projectOnto(seed, current)` | the current values at the keys the seed writes, the input for `seedHash` on a re-run | | `editedSinceSeed({ doc, currentHash, hashField, untouchedSeconds })` | `null` when untouched, otherwise why the record counts as edited | Types: `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess`, `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `SeedTarget`, `SeedValue`, `UpsertOptions`, `WriteLocalesOptions`, `EditedSinceSeedArgs`. ## Turn off, override, extend Every guard is a default. Change it with an env var at run time or with a `createSeeder` option in the script: | Env var | `createSeeder` option | Default | What it does | |---|---|---|---| | `SEED_DRY_RUN=1` / `--dry-run` | `dryRun` | off | no writes, print the plan | | `SEED_UPDATE=1` | `update` | off | update records nobody edited since seeding | | `SEED_ONLY` | `only` | all records | the records the run may touch: `pages:kontakt`, `forms:Contact form`, `global:header`, `pages:*` (comma-separated in env) | | `IPAL_SEED_ALLOW_FULL=1` | `guard.allowFull` | off | allow a run without `only` on production or a non-local database (a full re-seed — owner's OK only) | | `IPAL_SEED_ALLOW_PROD_UPDATE=1` | `guard.allowProdUpdate` | off | allow `update` on production or a non-local database | | `SEED_FORCE=1` | `force` | off | with `update`: overwrite edited records too. Local database only (`guard.forceOnlyLocal: false` lifts that) | | `SEED_LOCAL_HOSTS` | `guard.localHosts` | — | extra hosts that count as local, comma-separated (e.g. a Docker Compose `db` service) | | `SEED_DB_URL_ENV` | `guard.databaseUrl` | `DATABASE_URI` | the env var that holds the database URL / the URL itself | | `NODE_ENV` | `guard.production` | `NODE_ENV === 'production'` | whether this run counts as production | | — | `guard: false` | on | turn the production guard off (the project takes the risk) | | `SEED_UNTOUCHED_SECONDS` | `editCheck.untouchedSeconds` | `120` | the timestamp window for "untouched since creation" | | `SEED_HASH_FIELD` | `editCheck.hashField` | `seedHash` | the hash field name; empty / `false` = timestamps only | | — | `context` | `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }` all `true` | merged over the defaults; set a key to `false` to drop it | | — | `pagesCollection` | `pages` | the collection `{ $page }` links resolve in | | — | `formsCollection` | `forms` | the collection `{ $form }` links resolve in (by `title`) | | — | `label`, `log` | `[seed]`, stdout | line prefix and where lines go | | `SEED_NOTIFY_EMAIL` | — | — | form seed: notification address for a first run when the company global is still empty | The plugin has no seed option and runs no seed by itself. The templates are plain project scripts: edit them freely, but keep the rules above.