Operations

Lifecycle Hooks

Code that runs when the CMS starts, after an import and on unexpected errors.

Lifecycle hooks belong to the CMS itself, not to one collection. They fill a new database, run code on every start, rebuild data after an import and report errors. For hooks on reads and writes, see Hooks.

tenon.config.ts
export default defineCms({
  // ...
  seed: async ({ cms }) => {
    await cms.create("posts", { title: "Welcome" });
  },
  onInit: async ({ cms }) => {
    const site = await cms.getGlobal("general");
    console.log(`Serving ${site.title}`);
  },
});

When they run

Each hook has one job:

HookRunsUse it to
seedOnce per databaseFill a new database with starter content
onInitOn every start, after seedCheck settings, warm a cache or log the start
afterImportAfter cms.import() or a restore commitsRebuild what the content hooks keep up to date
afterErrorOn an unexpected errorReport the error to a service like Sentry

Nothing runs when your app imports tenon.config.ts. The first database query of a process runs these steps once:

  1. The migrations
  2. seed, once per database
  3. onInit
  4. The query itself

Every other query waits until the steps are done. If seed or onInit throws, that query fails, and the next query tries again.

  • Each hook gets cms, the server API. It skips the access rules and is untyped.
  • Plugins set the same hooks on definePlugin(). They run in the order of plugins, then the hooks of defineCms().

Seed

seed fills a new database, for example with sample content or a backup archive:

tenon.config.ts
import { openAsBlob } from "node:fs";

export default defineCms({
  // ...
  seed: async ({ cms }) => {
    await cms.import(await openAsBlob("seed/content.zip"));
  },
});
  • Your seed runs only when the database has no documents and no globals. A site that adds seed later is not seeded.
  • A plugin's seed runs the first time the plugin starts on a database, also on one with content. Plugins use it to install defaults.
  • A table records which seeds ran, so each seed runs once per database.
  • All seeds of one start run in one transaction. If one throws, nothing is kept, and all of them run again on the next start. Media files that a seed uploads stay in storage.
  • Use the cms the seed gets. Inside the transaction, another instance waits forever on a database with one connection.

To make a seed archive, build the content in the admin, then download it under Manage → Backup. See Backup and restore and the Seed content recipe.

onInit

onInit runs on every start, after the seeds and before the first request.

Serverless hosts start a process often, sometimes for each request. Keep onInit fast, and safe to run many times.

afterImport

An import writes rows straight into the database and skips the content hooks. afterImport runs after cms.import() or tenon restore commits, so you can rebuild what those hooks would have kept up to date:

tenon.config.ts
import { rebuildSearchIndex } from "./search";

export default defineCms({
  // ...
  afterImport: async ({ cms, mode }) => {
    await rebuildSearchIndex(cms);
    console.log(`Import done (${mode})`);
  },
});

mode is "replace", "merge" or "missing", and counts holds the number of imported rows. If the hook throws, the import call throws too, but the imported content stays.

afterError

afterError gets every unexpected error, for example to report it to Sentry:

tenon.config.ts
import * as Sentry from "@sentry/node";

export default defineCms({
  // ...
  afterError: ({ error, source, request, job }) => {
    Sentry.captureException(error, { tags: { source }, extra: { url: request?.url, job } });
  },
});

source says where the error happened:

sourceWhen
requestA route answers 500. Expected errors, like 400, 401 or 404, skip it
jobA job attempt throws. job has id, task, attempts and maxAttempts
seedA seed throws
initonInit throws
  • An error that afterError throws is logged and dropped.
  • An error in a local API call from your own server code reaches your own catch, not afterError.
The content hooks have an afterError stage too, in hooks. It runs for a failed operation on a collection, with the operation. The lifecycle afterError also sees jobs and the start. Use it for error reporting.