Files
ipal-kit/docs/seeding.md
T
Radosław SmolińskiandClaude Opus 5.5 cff76c2a69 Seed helper: @intecion/ipal-kit/seed (createSeeder + building blocks)
createSeeder(payload, { dryRun, update, force, guard, editCheck, context, ... })
returns upsertBySlug, upsertBy, fillGlobal and summary(); building blocks
isLocalDatabase, writeLocales, seedHash, projectOnto, editedSinceSeed.
Behaviour follows docs/seeding.md: create-only by default, natural keys,
never deletes, globals get empty fields only, every locale written with
fallbackLocale: false onto the same row ids, records edited since seeding
skipped, update refused on production / non-local DB unless
IPAL_SEED_ALLOW_PROD_UPDATE=1, context.ipalSkipIndexNow on every write.

Both seed templates now use the helper. Node-only entry (no 'server-only',
which throws under `payload run`). SQLite integration tests cover the
production guard, the edited-record skip, the hash field, row ids and
the IndexNow skip. Agent guide (AGENT.md, ipal-reference, ipal-site,
ipal-form) and seeding.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 18:33:34 +02:00

14 KiB

seeding — content seeds that never overwrite production

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-<name>.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), 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. 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.

  5. Globals: fill only empty fields. A field that already has content is kept.

  6. Media: leave upload fields empty or reference existing uploads by ID. Never upload files in a production seed. The editor adds images.

  7. Write each locale separately, with fallbackLocale: false. See Locales.

  8. Pass the context flags the plugin reads. See 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

--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)
error the write failed; the script exits with code 1

The summary table counts created, skipped, updated, skipped-edited and errors.

Before you run a seed on production

  1. Dry run. Run the seed with SEED_DRY_RUN=1 and read every line. Expect create and skip (exists).
  2. Test on a copy. Run it on staging or on a local copy of the production database first.
  3. Back up the database.
    • Coolify: the database resource → Backups → Backup now (deployment.md §4.6).
    • Postgres by hand: pg_dump -Fc "$DATABASE_URI" > before-seed.dump
    • MongoDB by hand: mongodump --uri="$DATABASE_URI" --archive=before-seed.archive
  4. 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.

// 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.

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) no revalidatePath for seeded records (outside Next the hook already does nothing)
ipalSkipIndexNow: true the IndexNow hook (indexNow option, 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).
  2. Dry run: SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts.
  3. Back up the database (Backup now).
  4. The real run, without SEED_DRY_RUN.

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.

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)
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.

// scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts
import config from '@payload-config'
import { createSeeder } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload'

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. { $page: 'kontakt' } becomes the ID of the page whose default-locale slug is kontakt.

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 (without fields that hold $page links), then every record gets its full content, so pages can link to each other in any order
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). 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) 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.

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
isLocalDatabase(url, { localHosts }) the "local database" test of 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 nulls 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: 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
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
— 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.