ObjectStackObjectStack

Seed data — fixtures and demo datasets

Populate ObjectStack objects with bootstrap data, reference records, and demo fixtures using defineSeed()

defineSeed() is the canonical way to define seed data in ObjectStack. It checks every record key against your object definition, so a typo in a record field name is caught before any row is loaded: by TypeScript for a record you write inline, and by defineSeed() itself, for every record, when the config is loaded (objectstack validate, objectstack build, boot).

Use seed data for:

  • System bootstrap — default roles, admin users, system configuration
  • Reference data — countries, currencies, ISO codes, standard picklist values
  • Demo / test fixtures — realistic sample records for development and CI

Quick Start

import { defineSeed } from '@objectstack/spec/data';
import { Account } from './objects/account.object';

export const accountsSeed = defineSeed(Account, {
  externalId: 'name',      // field that matches a record to an existing row on replay
  env: ['dev', 'test'],    // only load in dev and test environments
  // mode omitted → 'ignore': create-only, a replay never overwrites an edit
  records: [
    {
      name: 'Acme Corporation',
      type: 'customer',
      industry: 'technology',
      annual_revenue: 5000000,
    },
    {
      name: 'Globex Industries',
      type: 'prospect',
      industry: 'manufacturing',
      annual_revenue: 12000000,
    },
  ],
});

The first argument is the object definition (the exported constant from your object file), not a string. This lets defineSeed() check every field name in records against the object's fields map. See Type Safety for which half TypeScript checks and which half the call checks.

Import defineSeed from @objectstack/spec/data. Do not confuse it with defineDataset (from @objectstack/spec/ui), which is the unrelated ADR-0021 analytics-dataset helper — it takes a single config object and is not a seed factory.


Import Modes

The mode field controls how the seed runner behaves when it encounters an existing record (matched by externalId).

Seeds are replayed, not applied once: a seed loads again on every boot of a single-tenant runtime (production included), on every package install or upgrade, and on every publish. The mode decides what each of those replays does to a row a customer has since edited.

ModeBehaviorUse Case
ignoreDefault. Create-only: insert a record whose row is missing (a boot or organization replay skips one a person deleted), leave an existing row exactly as it isBusiness and starter data the customer owns once it is loaded
upsertCreate if new (a boot or organization replay skips one a person deleted), and on every replay write each declared column back onto the matched rowReference data the package must keep current
updateUpdate only, skip if not foundMigration patches on existing rows

Every mode matches on externalId, so a replay finds the row an earlier load wrote. The unkeyed modes insert and replace are retired: see Moving off insert and replace.

ignore — The Default (Create-Only)

defineSeed(Account, {
  externalId: 'name',
  // no mode: a replay inserts a missing account and leaves an edited one alone
  records: [
    { name: 'Acme Corporation', industry: 'technology' },
    { name: 'Globex Industries', industry: 'manufacturing' },
  ],
});

A seed with no mode never writes over a row that already exists. A customer who renames an account, or a job that advances a status, keeps that change across every restart and upgrade. The flip side: a value you later change in the seed reaches only a row the load creates. To see a seed edit in development, start from a clean database (os dev --fresh).

upsert — Reference Data the Package Keeps Current

defineSeed(Currency, {
  externalId: 'code',
  mode: 'upsert',   // every replay writes these columns back onto the matched row
  records: [
    { code: 'USD', name: 'US Dollar',    symbol: '$' },
    { code: 'EUR', name: 'Euro',         symbol: '€' },
    { code: 'GBP', name: 'British Pound', symbol: '£' },
  ],
});

Declare upsert only for data the package must keep refreshed. Every replay puts each declared column back, so an edit a customer made to such a row is overwritten on the next boot or upgrade, silently. To refresh most columns but leave the ones a customer or a job owns, mark those columns create-only — see applyOn: 'create'.

The default used to be upsert. A package built before the change carries a written mode: "upsert" on every dataset in its compiled artifact (the build stores the parsed seed), so it keeps replaying with upsert until it is rebuilt. A package installed with os package install keeps the body it was installed with, and its sample-data reseed replays that body, so it also has to be re-installed from the rebuilt artifact. Rebuild (and re-install) to take the create-only default; declare mode: 'upsert' on the datasets that must stay current.

Moving off insert and replace

insert and replace matched no existing row, so every replay inserted each record again: a 3-row fixture became 6, then 9 (#3434), and a person reference the first load had to leave empty stayed empty on the first row while only a later copy named the person. replace expected the caller to clear the table first, and no load ever clears one. Both were removed in @objectstack/spec 18.7.0 (#34613):

  • Authoring refuses them. defineSeed, defineStack, os validate, os build and the metadata save and publish doors reject mode: 'insert' or mode: 'replace' with a message that names the fix.
  • A stored dataset is refused alone. A package or a compiled artifact (objectstack.json) built before the change, or a seed already stored, can still carry one. The environment still boots: the boot seed, the organization replay, the dev hot reload and a package install or upgrade refuse that one dataset. It writes nothing, the load reports it as an error with the same message, and every other dataset and definition loads.
  • Rows already duplicated stay. Earlier replays wrote them as data; nothing deletes them. Remove the extra copies yourself if they matter.

To convert a dataset, declare which field identifies a row, then drop the mode (or declare upsert for reference data the package keeps current):

  1. A field names the row (a code, a slug, an email): set externalId to it.
  2. No single field does (a join table, a line item under a parent): set externalId to the list of fields that together identify a row, for example ['team', 'project']. Reference fields are matched by their resolved ids. A reference the first load has to leave empty (a person who has not signed up yet) still belongs in the key: each later load finds that row again by the key as authored, and the load that can resolve the person fills it in. See Composite natural key.
  3. The records carry their own ids: set externalId: 'id'.
// Before — refused since @objectstack/spec 18.7.0
defineSeed(ExchangeRate, {
  mode: 'replace',
  records: [{ key: 'USD_EUR', rate: 0.92 }],
});

// After — one row per key, written once
defineSeed(ExchangeRate, {
  externalId: 'key',
  records: [{ key: 'USD_EUR', rate: 0.92 }],
});

Rebuild the package (and reinstall it where it was installed with os package install) so the stored body carries the new declaration.

A Deleted Seed Row Stays Deleted

Each organization records which seed rows landed in it, by externalId, in the platform object sys_seed_landed_key. When a person deletes a seeded row, the next boot or organization replay does not insert it again: an ignore or upsert dataset inserts a missing row only if its key never landed in that organization. A row an upgrade adds to the seed has never landed, so it is still inserted. A reference to the deleted row from another seed row is left unwritten rather than reported as an error.

The record is kept and honoured where a load seeds a known organization: the single-tenant boot seed (objectstack serve, os start, on every restart; a multi-tenant boot seeds through the per-organization replay instead), the per-organization replay (seed-replayer, the marketplace's fallback one included, which it registers when no app has seed data), the dev hot reload, and a package install or upgrade (os package install, the marketplace install, into the installing person's organization) with its restart heal. A seed publish keeps no record, so a deleted row comes back on that. So do a load with no organization and a composition that does not register sys_seed_landed_key (@objectstack/platform-objects).

A row deleted before any load recorded it comes back once, on the first load that keeps the record, and stays deleted from then on. For the boot seed that is the first boot after the upgrade. An installed package records nothing until its next install, upgrade, reseed, replay or restart heal, so a row deleted before that load, even after the upgrade, comes back on it.

To bring the deleted rows back on purpose, a host or plugin calls the seed-replayer kernel service with { reseed: true }:

const replay = ctx.getService('seed-replayer');   // ctx: the plugin's context
await replay(organizationId, { reseed: true });   // inserts every missing seed row

For an installed package, the sample-data reseed (POST /api/v1/marketplace/install-local/:manifestId/reseed-sample-data) does the same in the caller's organization.


Seeds and State Machines

A seed is a curated snapshot of established facts — a project already completed, an opportunity already closed_won — not a record walking its lifecycle. So a seed write is exempt from the object's state_machine rule (#3433): it may be born in any state, and neither initialStates (the insert entry guard) nor transitions (the update guard) is enforced. Without this exemption a fixture that seeds a mid-lifecycle status would be silently rejected on the first boot, taking its lookup children down with it — the "installed but no data" trap.

The exemption is scoped to the state machine only. Every other validation still runs, so a seeded value must still be a valid field option and pass format, cross_field, and the rest. And os validate warns when a seeded value is not a state the machine declares (seed-value-outside-state-machine), so a typo like 'complete' for 'completed' still surfaces before boot.


Columns Your App Owns After the First Seed — applyOn: 'create'

An upsert replay re-asserts every column a record declares on the row it matched. That is right for master data and wrong for a column the app itself owns once the row exists: a status a scheduled job advances, a flag a job sets after it sends a notice, a reference a workflow re-points. Replayed, the seed would put those back, undoing the job's work on every boot.

Declare such a column applyOn: 'create' under columns:

defineSeed(Instalment, {
  externalId: 'code',
  mode: 'upsert',
  columns: {
    status:      { applyOn: 'create' },   // the payment job owns it after the first seed
    is_expiring: { applyOn: 'create' },   // the renewal job sets it
  },
  records: [
    { code: 'INS-001', amount: 1200, status: 'pending', is_expiring: false },
  ],
});
  • When the seed creates the row, every column is written, status and is_expiring included.
  • When a replay matches an existing row, status and is_expiring are left out of the write: the row keeps the values the jobs gave it, while amount (applyOn: 'always', the default) is refreshed. A row whose only differences are create-only columns is not written at all.
  • An update dataset never writes a create-only column. ignore never updates a matched row, so the policy changes nothing there.
  • A create-only reference on a matched row is not resolved at all, so a replay neither re-points it nor reports it.
  • A column of the externalId is what the row was matched by, so it stays in the update whatever it declares.

applyOn takes the same values, with the same default and meaning, as an import mapping entry's applyOn. A columns key must name a field of the object (or a system column the platform injects on it, such as owner_id): defineSeed refuses one that does not, and the loader logs an error naming the column whenever it loads a seed that names one, since a stored seed never passes through defineSeed.


Environment Scoping

The env array controls which deployment environments receive the records. The default is ['prod', 'dev', 'test'] — all environments.

// Reference data — safe for all environments (default)
defineSeed(Country, {
  // env omitted → defaults to ['prod', 'dev', 'test']
  records: [
    { code: 'US', name: 'United States' },
    { code: 'GB', name: 'United Kingdom' },
  ],
});

// Demo data — never reaches production
defineSeed(Account, {
  env: ['dev', 'test'],
  records: [
    { name: 'Demo Corp', type: 'customer' },
  ],
});

// Automated test fixtures — CI/CD only
defineSeed(TestUser, {
  env: ['test'],
  records: [
    { email: 'ci-admin@example.com', role: 'admin' },
  ],
});

Locale Scoping

The locale array scopes a dataset to one or more language markets, as BCP-47 tags. It is a second filter axis alongside env, and the two compose: a dataset loads when it passes env and locale.

Omitting locale means every locale — unlike env there is no default array, because locales are open-ended tags with no closed set to spell out.

// Reference data — every market (locale omitted)
defineSeed(Country, {
  records: [{ code: 'US', name: 'United States' }],
});

// The Chinese market's demo plans
defineSeed(Plan, {
  locale: ['zh-CN'],
  records: [{ name: '专业版', price: 99 }],
});

// The same plans for English-speaking markets
defineSeed(Plan, {
  locale: ['en', 'en-GB'],
  records: [{ name: 'Professional', price: 15 }],
});

Tags are matched case-insensitively (zh-cn and zh-CN are the same tag) and otherwise exactly — ['zh'] does not match a loading locale of zh-CN. List every tag the dataset is for.

The platform does not translate anything. locale only selects between record sets you authored yourself; both sets stay in your source tree, and the choice is made when the seeds load rather than when your config is assembled — so switching markets does not mean rebuilding, and the axis is evaluated in the one layer that could ever reconcile rows already written for another market.

It does not reconcile them, though. As Import Modes above states, the loader never deletes anything itself — every mode only ever writes. So switching a stack's active locale on a non-empty database loads the new locale's dataset alongside the rows the previous locale's dataset wrote: both sets stay resident and queryable, because the switch is additive and not a migration. Clearing the market you left behind is the operator's job — to switch locales cleanly, start from a fresh database.

A Fallback Set — fallback: true

A locale that no dataset of an object names gets none of that object's locale-scoped rows. Where the seed is functional rather than decorative — the standard price book that quotes fall back to — an organization on ja-JP would end up with no price book at all when you ship only a zh-CN and an en set. Mark one set fallback: true and it also loads for every locale no other set of the object names:

defineSeed(PriceBook, {
  locale: ['zh-CN'],
  records: [{ name: '标准价格表' }],
});

defineSeed(PriceBook, {
  locale: ['en', 'en-US'],
  fallback: true,          // also loads for ja-JP, es-ES, … — any locale no PriceBook set names
  records: [{ name: 'Standard' }],
});
Resolved localePriceBook rows loaded
zh-CNthe zh-CN set
en, en-USthe en set (its own locales)
ja-JP, es-ES, …the en set, as the fallback
none (package apply, draft publish, an unresolved install)both sets, with the usual warning

The rules:

  • The fallback set lists its own locales. fallback: true on a dataset with no locale is refused when the seed is parsed: an unscoped dataset already loads for every locale, so it cannot also be the set that loads only when no other set matches. Write the locales the set is in and keep the marker.
  • A set with no locale does not count as a match. It is locale-neutral: it loads beside whichever set is chosen, and the fallback still fills in.
  • Matching is per object, case-insensitive and otherwise exact, as above. A ja-JP set of some other object does not stop the price book's fallback.
  • env is applied first. A set env scoped out of the load neither matches nor falls back.
  • At most one fallback set per object in a load. Two different sets of one object both marked fallback: true leave no single choice, so only the fallback choice is refused: no marked set fills in for a locale no set lists, and the load's error (also logged at warn) names the object. Every marked set still loads for the locales it lists, exactly as an unmarked set would, and every other object still seeds. Identical copies of one set — the same package's datasets merged twice — count once. Two versions of one package whose marked set changed are two sets: an upgrade keeps the earlier version's datasets on the per-organization replay list until the process restarts, so until then an organization on an unlisted locale gets no fallback for that object.

The loader logs, at info, each fallback set it loaded and the locale it filled in for. Datasets without the marker load exactly as before.

Where the loading locale comes from. On the normal boot path your stack supplies it: the runtime reads your app's i18n.defaultLocale and passes it to the seed loader, so declaring a locale on a dataset takes effect with no extra wiring. Declare no i18n block and no locale is sent at all — which is the unrestricted setting, not a filter.

Installs and new organizations load for the organization's language. A marketplace install, a sample-data reseed, the restart heal of an installed package, and the replay that seeds each new organization pick the locale for the organization the rows land in. The first of these that answers wins:

  1. the organization's Setup → Localization → Default language, when somebody set it, for that organization or for the whole deployment (the built-in en-US default does not count as set);
  2. the language of the person installing, reseeding or creating the organization;
  3. the app's i18n.defaultLocale.

So one package can ship a Chinese and an English demo catalogue side by side, and a Chinese organization gets the Chinese one. A new organization has no Localization setting of its own yet, so its creator's language decides, and one created with no person behind it takes the app's default. On a runtime whose seed data comes only from marketplace packages, a new organization's replay skips the third step: it replays every installed package at once, and no one package's default speaks for all of them.

The axis is evaluated against the seed loader's config.locale. A host that supplies no locale — an app with no declared i18n.defaultLocale, or an embedding host that builds its own seed-load request — gets every dataset, and the loader warns naming each locale-scoped dataset it let through, so a scope that is not taking effect is one log line to diagnose rather than a silent no-op.

Applying a package and publishing a draft are locale-neutral. Those two build their own seed-load request and pass no locale, so a locale-scoped dataset reaching one of them loads for every market and is named in that warning. Installing from the marketplace was locale-neutral too until the install paths started picking by the organization's language, above (ruled 2026-11-05 on #30281, which reverses the install half of #17011).


Type Safety

A record key must name a column of the object: a field it declares, or a system column the platform injects on it (id, organization_id, created_at, created_by, updated_at, updated_by, owner_id, owning_business_unit_id, unless the object opts out of them with systemFields, tenancy, ownership or managedBy). defineSeed() checks this twice.

At compile time, for a record written as an object literal directly in records, TypeScript reports an unknown key immediately:

import { Account } from './objects/account.object';

defineSeed(Account, {
  records: [
    {
      name: 'Test Corp',
      typo_fild: 'value',
      //  ^^^^^^^^^
      //  TS Error: Object literal may only specify known properties,
      //  and 'typo_fild' does not exist in type 'SeedRecord<...>'
    },
  ],
});

This is TypeScript's excess-property check, so it does not see a record that is not a fresh literal in the call: one from a variable or a .map(), any inline record in an array that also spreads a Record<string, unknown>[], or a record for an object typed ServiceObject. It admits every system column name, because a type cannot evaluate the object's opt-outs.

When the call runs (when objectstack validate, objectstack build or boot loads your config), defineSeed() checks every record, whatever its shape, against the object's declared fields and the system columns injected on that object, and refuses the seed naming each unknown key:

defineSeed('crm_account'): unknown field(s) in records — typo_fild.
  • records[0]: `typo_fild` is not a field of `crm_account`.

This is a major advantage over writing plain JSON — always use defineSeed() over the raw SeedSchema.parse() call, which checks no record key.


Relationship Fields

For lookup fields that reference another object, supply the natural key value of the related record (such as name, email, or code) — not its UUID. The seed runner resolves natural keys to database IDs automatically at load time.

// Step 1 — seed the parent object first
const accountsSeed = defineSeed(Account, {
  externalId: 'name',
  records: [
    { name: 'Acme Corporation', type: 'customer' },
  ],
});

// Step 2 — seed the child object, referencing the parent by natural key
const contactsSeed = defineSeed(Contact, {
  externalId: 'email',
  records: [
    {
      email: 'john.smith@acme.example.com',
      first_name: 'John',
      last_name: 'Smith',
      account: 'Acme Corporation',   // natural key, not a UUID
    },
  ],
});

// The loader puts accounts first because `contact.account` looks them up
export const SeedData = [accountsSeed, contactsSeed];

References on an organization's own load

A load that seeds one organization (the per-organization replay, a reseed, a package install into an organization) resolves a natural key inside that organization, by what the target object carries:

TargetResolves to
An object with an organization_id column (every business object)a row of the load's organization only; another organization's row with the same key is never used
sys_user (people: owner_id, people lookups)a person who is a member of the load's organization (a sys_member row there); a same-named person outside it is never used
sys_organizationthe load's own organization only
An object no organization walls: no organization_id column and no tenant field (for example tenancy: { enabled: false })any row: global rows belong to every organization
An object walled by another tenant column (tenancy.tenantField) with no organization_id columna row of the load's organization only, matched on that tenant column (the column a seeded row of such an object is stamped with); another organization's row with the same key is never used

A load with no organization (the single-tenant boot) resolves across the whole database, as it always has. When the database refuses a lookup outright (for example a column the target does not have), the load logs the refusal once, with its code, and the reference's error says the lookup was refused instead of claiming the row does not exist.

Multi-Value Lookups (multiple: true)

A lookup declared multiple: true stores an array of related record ids, so its seed value is an array of natural keys. Each element resolves independently.

const Book = ObjectSchema.create({
  name: 'book',
  sharingModel: 'private',
  fields: {
    name: Field.text({ label: 'Title', required: true }),
    authors: Field.lookup('author', { label: 'Authors', multiple: true }),
  },
});

const booksSeed = defineSeed(Book, {
  externalId: 'name',
  records: [
    { name: 'Refactoring', authors: ['Alice', 'Bob'] },  // one natural key per author
  ],
});

A lone string is accepted as one-element shorthand (authors: 'Alice' stores [<alice id>]). Resolution is all-or-nothing per field: if any element is still missing, the whole array is deferred to pass 2 rather than written half-resolved, and a key that never materializes is reported as a load error naming that element.

Passing an array to a single-value lookup is rejected with a load error — declare the field multiple: true, or pass one natural key.

Composite externalId — Join / Junction Tables

A join (junction) table linking two objects many-to-many has no single-field natural key — the pair of foreign keys is what makes a row unique. Pass a list of field names as the externalId so the seed runner can match existing rows on the composite key and stay idempotent across replays. The foreign keys are compared by their resolved record ids, which are stable between boots.

// A team can staff many projects; a project can have many teams.
// `showcase_project_membership` is the join row — unique on (team, project).
const membershipsSeed = defineSeed(ProjectMembership, {
  mode: 'ignore',                     // skip pairs that already exist
  externalId: ['team', 'project'],    // composite natural key — both FKs
  records: [
    { team: 'Experience', project: 'Website Relaunch', engagement: 'owner' },
    { team: 'Platform',   project: 'Data Platform',    engagement: 'owner' },
    { team: 'Platform',   project: 'Website Relaunch', engagement: 'contributor' },
  ],
});

Without a composite key such a table has nothing to match a replay on. The unkeyed mode: 'insert' it once fell back to duplicated on every replay boot (#3434) and is retired.


Load Order — dependsOn

A load orders its datasets by the relationships between their objects: a lookup, master_detail or user field makes its object load after the object it points at, however the datasets are listed. The order of your data array only breaks ties between objects that are ready at the same moment.

Some dependencies are not fields. A beforeInsert hook that reads another seeded object while a row is written (a rating scored from seeded bands, a price computed from a seeded rate table) needs those rows to be there first, and no lookup says so. Declare it with dependsOn, naming the objects:

export const ratingBandsSeed = defineSeed(RatingBand, {
  externalId: 'code',
  records: [/* … */],
});

// The rating's beforeInsert hook scores each row from crm_rating_band rows,
// so this dataset must load after them.
export const customerRatingsSeed = defineSeed(CustomerRating, {
  dependsOn: ['crm_rating_band'],
  records: [/* … */],
});

Each name adds an edge to the same dependency graph the lookup fields feed. A dataset that declares no dependsOn loads exactly where its lookups put it.

The loader refuses the whole load, writing no row, and reports why, when a dependsOn:

  • names the dataset's own object (defineSeed also refuses this when it runs);
  • names an object no other dataset of the same load seeds: a misspelling, or a dataset that env or locale scoped out of this load. A seed published on its own is its own load, so publish it together with the seeds it depends on. Two more loads carry only part of an app's seeds and refuse the same way: the dev hot-reload seeder loads only the datasets of objects first seen in that reload, so restart the dev server after adding a seed that depends on an object seeded earlier, and a marketplace install loads one package's datasets, so name only objects your own package seeds;
  • closes a cycle with the other edges, lookups included: crm_rating_rule declaring dependsOn: ['crm_customer_rating'] while the rating looks up its rule. No order can keep that edge.

A cycle made only of lookup fields is still loaded in several passes (each row is written first and its missing reference filled in afterwards), as before.


File Fields — seedFile(path)

A file, image, avatar, video or audio field stores the id of a stored file, and a seed has no upload to make one. Name the file by the path your package ships it at instead, and the platform stores it for the record:

import { defineSeed, seedFile } from '@objectstack/spec/data';

export const contractVersionsSeed = defineSeed(ContractVersion, {
  externalId: 'code',
  records: [
    { code: 'NDA-001-V1', file: seedFile('fixtures/nda-v1.pdf') },
    // `name` is what a download is saved as; `contentType` for an extension
    // the build does not know.
    { code: 'MSA-001-V1', file: seedFile('fixtures/msa-v1', { name: 'MSA v1.pdf', contentType: 'application/pdf' }) },
    // A `multiple: true` file field takes an array.
    { code: 'SOW-001-V1', file: seedFile('fixtures/sow.pdf'), scans: [seedFile('fixtures/p1.png'), seedFile('fixtures/p2.png')] },
  ],
});
  • The path is relative to the directory holding objectstack.config.ts and stays inside it — / separators, no leading /, no . or .. segment.
  • os build reads each referenced file and bundles its bytes into the compiled artifact, so the seed carries them wherever the artifact goes (os dev, os serve, a published package). A path that names no file fails the build, and os validate refuses it too. os serve booting the config itself reads the files the same way.
  • The seed load stores each file and writes its id into the field; the record owns the file exactly as if it had been uploaded into that field. Every row gets a file of its own, even when two rows name the same path. A replay keeps a file whose bytes did not change, so restarting does not store it again; changing the file and rebuilding replaces it.
  • Refused, by row, loudly: a reference whose bytes the build did not bundle (a dataset written by hand without its files), bytes that do not match what the build recorded, and a file field holding an id-shaped string that names no stored file — write seedFile(...) there instead.

Dynamic Values (CEL)

Any field value may be a CEL expression evaluated at install time against a single per-load pinned now. This is the only correct way to author time-based or identity-derived seed values — a literal new Date() would ship the package author's clock to every customer and break build determinism.

import { defineSeed } from '@objectstack/spec/data';
import { cel } from '@objectstack/spec';

defineSeed(Opportunity, {
  records: [{
    name:            'Acme Q3 Renewal',
    close_date:      cel`daysFromNow(45)`,
    created_at:      cel`now()`,
    owner_id:        cel`os.user.id`,   // the seed identity
    organization_id: cel`os.org.id`,
  }],
});

Available in the seed CEL context:

  • Functions: now(), today(), daysFromNow(n), daysAgo(n), isBlank(v), coalesce(v, fallback)
  • Scope: os.user, os.org, os.env

Owner-style fields (owner_id, created_by, assigned_to)

Many objects have an owner lookup — owner_id, created_by, assigned_to. On a fresh boot there are no human users yet — seed data loads before the first sign-up — so the platform does not mint a placeholder system user to own these fields. The recommended pattern is to leave owner-style fields unset in the record:

defineSeed(Project, {
  externalId: 'code',
  records: [{
    code: 'bootstrap',
    name: 'Bootstrap Project',
    // owner_id intentionally omitted — filled in by the first-admin handoff below
  }],
});

What actually happens to os.user? The seed loader binds os.user to whatever identity the load run carries (config.identity). During the normal boot sequence no identity is supplied, so os.user resolves to a null identity and cel\os.user.id`evaluates tonull— the record still seeds successfully, with the field leftnull rather than the load failing. Once the first human user is promoted to platform admin, an ownership handoff re-owns every orphaned row (owner_id null, or the legacy usr_system` value from older databases) to that admin. The handoff is not one-time: it runs again whenever a seed settles, on that boot and on every later one, so rows a later boot's seed replay inserts go to the existing platform admin the same way. A row someone already owns is never touched.

  • Because cel\os.user.id`resolves tonull` before an admin exists, a required (non-nullable) owner-style field must not depend on it — either leave the field optional/unset (recommended) or supply a literal value.
  • cel\os.user.id`still resolves to a real user id when the loader is invoked with an explicit identity (e.g. a re-seed run through tooling that passesconfig.identity`).
  • os.org.id resolves to the current organization; during a per-tenant replay it is that tenant's id, falling back to the load's organizationId.
  • Hooks run on seeded rows (seeds skip only flow automation), and a hook sees the organization the row is stamped with as ctx.session.organizationId, the same as for a row written through the API (a row that supplies its own organization_id is written as that organization). Under a walled tenancy posture its ctx.api reads, and every engine read the write triggers, are scoped to that organization. A load with no organization gives hooks none.

Failure is loud, not silent

If a record's CEL expression cannot be evaluated at all (a malformed expression, or a reference the CEL engine cannot compile), the record is not silently dropped. The loader counts it as an error, marks the load unsuccessful, and logs an actionable message:

[SeedLoader] Cannot resolve dynamic seed values for project record #0: <expression error>.
  `os.user.id` resolves to null at seed time (the owning admin does not exist yet) and
  owner-style fields are assigned by the first-admin handoff — so a required, non-owner
  field must not depend on it. Provide a literal value or make the field optional.

Separately, if the write itself fails after resolution (e.g. a NOT NULL column rejects a null value produced by an unresolved owner field), that surfaces as its own error:

[SeedLoader] Failed to write project record #0 (code=bootstrap): <driver error>

Both cases increment result.summary.totalErrored, add an entry to result.errors, and flip result.success to false. Tooling should check result.success / result.errors rather than assuming a clean run.


Organising Multiple Datasets

For applications with several objects, co-locate seed files under src/data/ and export a single aggregate array.

src/
  data/
    index.ts              ← exports SeedData array in dependency order
    accounts.seed.ts
    contacts.seed.ts
    leads.seed.ts
    products.seed.ts
// src/data/index.ts
import { accountsSeed }  from './accounts.seed';
import { contactsSeed }  from './contacts.seed';
import { leadsSeed }     from './leads.seed';
import { productsSeed }  from './products.seed';

/** All seed datasets — the loader orders them by their lookups and dependsOn */
export const SeedData = [
  accountsSeed,   // no dependencies
  productsSeed,   // no dependencies
  contactsSeed,   // looks up accounts, so it loads after them
  leadsSeed,      // no dependencies
];

Best Practices

Choose a stable externalId

The externalId field must be a stable natural key that does not change between environments. Avoid using the auto-generated id (UUID) because UUIDs differ between databases.

ScenarioRecommended externalId
Named entities (countries, currencies)'code' or 'slug'
User records'email'
Generic named records'name' (default)
Externally sourced data'external_id'
Join / junction tables (no single natural key)a composite list, e.g. ['team', 'project']

Scope demo data with env

Keep demo and test-only records out of production by setting env: ['dev', 'test']. System bootstrap data that must exist in production should omit env (or explicitly set ['prod', 'dev', 'test']).

Ship one dataset per market, not one build per market

When the same records need different display strings per language, author both datasets and scope each with locale. Selecting between them in application code instead bakes the choice into your build output, so shipping another market means another build. Neither approach removes what the market you left behind already wrote — see Locale Scoping. Mark one set fallback: true so a market you did not author still gets functional rows — see A Fallback Set.

Leave mode unset for data the customer owns

The default, ignore, is idempotent and never overwrites an edit. Declare a mode only when the use case requires it — upsert for reference data the package keeps current (with applyOn: 'create' on the columns the customer or a job owns), or update for a migration patch on rows that already exist.

Declare a dependency no field expresses

Lookup fields order the load for you: if contact has a lookup to account, accounts load first wherever accountsSeed sits in the array. Listing parents first keeps the file readable, but it orders nothing. When a hook reads another seeded object, declare it with dependsOn (see "Load Order").

Keep records realistic

Demo data appears in screenshots, documentation, and live demos. Use realistic company names, email addresses, and values — not foo, bar, or test123.

One file per object

Split large seed payloads into {object}.seed.ts files. A single index.ts that re-exports and orders them keeps the entry point clean.


defineSeed() API Reference

function defineSeed<
  const TObj extends { name: string; fields: Record<string, unknown> }
>(
  objectDef: TObj,
  config: {
    externalId?: string | string[];         // single field, or a composite list (join tables); default: 'name'
    mode?: 'update' | 'upsert' | 'ignore'; // default: 'ignore'
    columns?: { [field: string]: { applyOn?: 'create' | 'always' } }; // per-column write policy; default: 'always'
    env?: Array<'prod' | 'dev' | 'test'>;  // default: ['prod','dev','test']
    locale?: string[];                      // BCP-47 tags; omitted = every locale
    fallback?: true;                        // also load for a locale no other set of the object names (needs locale)
    dependsOn?: string[];                   // objects this dataset loads after (see "Load Order")
    records: Array<SeedRecord<TObj['fields']>>;  // declared fields + injectable system columns
  }
): Seed

// A file the package ships, for a file-class field (see "File Fields").
function seedFile(path: string, options?: { name?: string; contentType?: string }): { $file: string; name?: string; contentType?: string }

SeedRecord keys are the object's declared fields (a lookup / master_detail field takes its target's natural-key string) plus the injectable system column names. Every record key, and every columns key, is checked again when the call runs.

The returned Seed object is a plain serialisable value — pass it to your stack's seed runner or store it in an export array.


Next: Data Modeling Guide

On this page