You're reading docs for Nextly Alpha. APIs may change between releases.

Plugins

Data access (ctx.services)

Read and write data from a plugin through the managed, secure-by-default service layer — queries, bulk operations, and system elevation.

ctx.services is the managed data path for plugins. Prefer it over the unmanaged ctx.db surface: it enforces validation, hooks, events, and RBAC, and it stays portable across database dialects. It is @public and semver-protected.

init(ctx) {
  const posts = await ctx.services.collections.listEntries(
    ctx.self.collections.posts, // resolve your own slugs via ctx.self
    { where: { status: "published" }, sort: { field: "createdAt", direction: "desc" } },
    { as: "system" }
  );
}

Secure by default

Every access method takes a trailing ServiceOpts ({ as, user }) that decides whose permissions apply:

optsBehaviour
{ as: "user", user }Runs as that caller — RBAC enforced. In a plugin route the caller's API-key scope is carried automatically, so a key is judged on its own grants rather than its owner's; pass authenticatedScope explicitly only to narrow it.
{ as: "public" }Runs as an anonymous visitor — the collection's access rules apply with no user. A read with no rule for it is allowed (the public default); a create, update or delete is refused unless the collection's rule for it answers true, such as access: { create: () => true } on a form's submissions.
{ as: "system" }Elevates — bypasses the access check for trusted, non-user work (jobs, derived data, lookups). Visible and greppable by design.
{} / omittedNo user → defaults to system (jobs, CLI, migrations).

Validation, hooks, and events always run, even under { as: "system" } — only the access check is skipped. So a system write still fires afterCreate hooks and emits events.

v1 limitation: under { as: "user" }, code-defined access rules that read ctx.user.role see it empty (RBAC is enforced by a DB lookup on user.id). Pass { as: "system" }, or rely on DB-level RBAC, when you need role-aware access.

Pick the elevation deliberately. A public route that lists published content should use { as: "system" } (the data is public-derived); a route that returns a user's own records should use { as: "user", user: ctx.user ?? undefined }.

Reading and writing in a locale

On a localized site, name the language beside the elevation. locale decides which translation a read answers with and which one a write stores into; absent, it is the site's default, which is what every call has always meant.

// A French visitor's page reads French content.
const frenchPage = await ctx.services.collections.findEntryById("pages", id, {
  as: "system",
  locale: "fr",
});

// A translation is written the same way: only the localized fields move. The
// version comes from the French read, which covers the French translation.
await ctx.services.collections.updateEntry(
  "pages",
  id,
  { title: "Merci", _rev: frenchPage._rev },
  { as: "system", locale: "fr" }
);

A missing translation is answered by the site's fallback chain, which is right when the page has to show something. Pass fallbackLocale: false when the question is whether the translation exists — a sitemap deciding whether to list a language, say — and the default's value standing in would mislead you.

A public read answers for its language only: an entry not published in that language is not found, even when its default is. Pass wholeDocumentFallback: true to findEntryById to read it instead in the first language of its fallback chain that it is published in, as ?fallback=document does on the REST API. The entry says which language answered in _locale, and each language is still read as the caller. Every other method refuses the option with a 400.

// A French visitor is sent to the French page once it is published, and to the
// published default until then.
const page = await ctx.services.collections.findEntryById("pages", id, {
  as: "public",
  locale: "fr",
  wholeDocumentFallback: true,
});

What an unconfigured code means depends on the verb, and deliberately so. A read resolves it to the default, the same way ?locale= does on the REST API, so a wrong query string still shows a page. A write is refused with a 400, so a typo cannot overwrite the default language's content. createMany refuses any locale at all, by name: its bulk pipeline writes rows in one pass and cannot store a translation, and an option it accepted but could not honour would file every row under the default language and report success. Create the rows one at a time with createEntry instead.

locale names one language. The selectors the core understands elsewhere — *, which moves every translation's lifecycle in one write, and all, which answers a read with one value per language — are refused here with a 400, so a value forwarded from a query string can never publish every translation of a document by accident. A plugin that needs the every-locale sweep needs a surface that says so by name; there is none yet. A route that forwards ?locale= and wants a wildcard to read as "no language" can ask the core which spellings are selectors — isLocaleSelector from @nextlyhq/plugin-sdk, @experimental until it ships in a release — rather than keep a list of its own. The same spellings are reserved at configuration — along with none, the wire's spelling of fallbackLocale: false — so a site cannot name a language all or none. An empty locale (what ?locale= with nothing after it forwards) reads as no language named, not as a wrong one.

deleteEntry refuses a locale too, by name: a delete removes the document and every translation with it, and there is no per-language delete — so { locale: "fr" } would read as "remove the French translation" and remove the English, the German and the row.

With that, the pair is spelled exactly as it is on the request context and on the wire, and a route can pass through what it was given: a wrong code shows the default on a read and is refused on a write, and a selector is refused on both.

Collection methods

ctx.services.collections exposes:

MethodPurpose
createEntry(slug, data, opts?)Create one entry. Returns { message, item, warnings? }.
listEntries(slug, query?, opts?)List with filter/sort/pagination → PaginatedResult.
findEntryById(slug, id, opts?)Fetch one by id.
updateEntry(slug, id, data, opts?)Update one; data carries _rev or _overwrite: true. Returns { message, item, warnings? }.
deleteEntry(slug, id, opts?)Delete one. Returns { message, item: { id }, warnings? }.
count(slug, where?, opts?)Count matching rows.
createMany(slug, rows, opts?)Bulk insert → BatchOperationResult.
updateMany(slug, entries, opts?)Bulk update, one { id, data } per row → BatchOperationResult.

It also has createCollection, listCollections, getCollection, updateCollection, deleteCollection, warmLocalizedReadiness, and the transaction methods.

Each service is a facade

Every service reaches your plugin as a frozen facade: an object holding only the methods meant for plugins, each calling the service's own method. The service's database adapter, Drizzle handle, sub-services and logger are not on it, so a plugin cannot reach the database through a service except by calling its methods.

ServiceTypeMethods
collectionsPluginCollectionServicethe methods above
usersPluginUserServicecreate, findById, listUsersByIds, findByEmail, listUsers, update, delete, authenticate, changePassword, hasPassword, updateProfile
mediaPluginMediaServiceupload, findById, listMedia, update, delete, bulkUpload, bulkDelete, moveToFolder, getStorageType, hasStorage, createFolder, findFolderById, listRootFolders, listSubfolders, getFolderContents, updateFolder, deleteFolder, isImage, validateImage, getImageDimensions, isInUse
emailPluginEmailServicesend, sendWithTemplate, queue, queueWithTemplate, forgetSends, onQueuedEmailChange, readQueued, recipientDigest, sendPasswordResetEmail, sendEmailVerificationEmail, sendWelcomeEmail, isConfigured, canSendTemplate
versionsPluginVersionsServicelist, get, setLabel, deleteWorkingDraft, autosave, getAutosave, pendingEditRows, and pins (version pins on the plugin's own transaction; see Pinning a version)

ctx.services also has singles (the declared Singles), jobs (queue background work) and plugins (services other plugins contribute). The service types are @experimental and exported from @nextlyhq/plugin-sdk.

Querying

listEntries takes a QueryOptions:

const result = await ctx.services.collections.listEntries(
  slug,
  {
    where: { status: "published", authorId: someId }, // filter (key/value)
    sort: { field: "createdAt", direction: "desc" }, // single-field sort
    pagination: { limit: 20, page: 1 }, // page through results
    depth: 1, // 0–5: how deep to populate relations (0 = ids only)
    select: { title: true, slug: true }, // projection: return only these fields
  },
  { as: "system" }
);

result.data; // the rows for this page
result.pagination; // { total, limit, offset, hasMore }

Use depth: 0 when you only need scalar fields (e.g. building a sitemap) — it avoids populating relations and is cheaper.

Bulk operations

createMany and updateMany return a BatchOperationResult, so a partial failure tells you exactly which rows failed and leaves the rest committed:

const res = await ctx.services.collections.createMany(slug, rows, {
  as: "system",
});
// { successful, failed, ids: string[], errors: [{ index, error }] }

updateMany takes one { id, data } per row, so a single call can apply a different patch to each row. Applying the same patch to many rows is the same call with the patch repeated:

const res = await ctx.services.collections.updateMany(
  slug,
  [
    // Each row says which version it changes (its `_rev`), or that it
    // replaces whatever is stored.
    { id: "post-1", data: { status: "published", _rev: "7" } },
    {
      id: "post-2",
      data: { status: "archived", pinned: false, _overwrite: true },
    },
  ],
  { as: "system" }
);

errors[].index indexes the array you passed, so the row a failure is about is entries[index].id. The result shape is shared with createMany, which has no caller-supplied ids to key its failures by.

To update every row matching a filter, list them first and map the ids. There is no by-filter batch update, deliberately: a filter that matches more than the author meant is the failure this surface has no way to take back.

listEntries returns one page, so page through it. The loop below re-reads page 1 each time on purpose: every updated row leaves the draft filter, so the rows that still match move up into it.

let updated = 0;
for (;;) {
  const page = await ctx.services.collections.listEntries(
    slug,
    { where: { status: "draft" }, pagination: { limit: 100 }, depth: 0 },
    { as: "system" }
  );
  if (page.data.length === 0) break;

  const res = await ctx.services.collections.updateMany(
    slug,
    page.data.map((row: { id: string; _rev: string }) => ({
      id: row.id,
      data: { status: "published", _rev: row._rev },
    })),
    { as: "system" }
  );
  updated += res.successful;
  // Nothing moved: the rest are failing rather than draining, so stop rather
  // than read the same page forever.
  if (res.successful === 0) break;
}

When the patch does NOT change what the filter matches, page with pagination: { page: n } instead and stop when pagination.hasMore is false, or the loop above would re-read the same rows.

Each row of updateMany carries its own _rev in its data, or _overwrite: true, and is judged on its own (see Versions and conflicts): a row saved since you read it comes back in errors with the code STALE_VERSION, a row that sends neither comes back with VERSION_REQUIRED, and neither writes anything. The other rows are applied.

Neither takes a locale: the bulk pipeline writes in one pass and cannot store a translation, so both refuse one by name rather than filing every row under the default language. Write the rows one at a time with createEntry or updateEntry when a language matters.

Writes return an envelope

createEntry, updateEntry and deleteEntry resolve to { message, item, warnings? } — the same shape the Direct API and the REST API return, so the same failure is equally visible however the write was made.

const { item, warnings } = await ctx.services.collections.createEntry(
  slug,
  data,
  { as: "system" }
);

if (warnings) {
  // The row IS saved. A post-commit hook (`afterCreate` and friends) runs once
  // the write has committed, so a handler failing there cannot un-save it —
  // report it, don't retry the write.
  ctx.logger.warn("side effects failed", { id: item.id, warnings });
}

deleteEntry reports item as { id }, since there is no row left to return.

Versions and conflicts

Every entry carries a version, _rev, on what findEntryById and listEntries return and on the item of every create and update. Pass it back in the update's data, and the update is applied only if nobody has saved the entry since you read it:

const post = await ctx.services.collections.findEntryById(slug, id, {
  as: "system",
});

const { item } = await ctx.services.collections.updateEntry(
  slug,
  id,
  { title: "Hello again", _rev: post._rev },
  { as: "system" }
);
// item._rev is the new version, for the next save

An out-of-date save throws a NextlyError with the code STALE_VERSION (409), and writes nothing: check it with NextlyError.isCode(err, "STALE_VERSION"). updateEntryInTransaction is judged the same way, so a refused update leaves the rest of your transaction to you. To save whatever the current version, add _overwrite: true to data; the entry's history records the overwrite. An update that sends neither throws VERSION_REQUIRED (428) and writes nothing.

What _rev covers and which writes are judged are the same for every caller; see the REST API's Versions and conflicts. ctx.services reads no Single's content, so a plugin has no _rev to send for a Single.

Rewriting one field on the live copy and its drafts

rewriteField is @experimental. It takes a top-level field of a collection entry or of a Single.

Some jobs change one value on many entries on nobody's behalf: moving pages off a layout before it is deleted, or turning the copies of a deleted component into plain blocks. An ordinary update can't do that safely on a published entry with a pending draft. Naming no status saves only the draft, and naming one publishes the author's unfinished draft.

rewriteField changes the field on the entry's live copy and on every pending draft that holds it, in one transaction, without publishing anything. Each draft stays a draft, and the entry's status doesn't change.

const page = await ctx.services.collections.findEntryById("pages", id, {
  as: "system",
});

const { version, copies } = await ctx.services.collections.rewriteField({
  collection: "pages",
  id,
  field: "layout",
  expectedVersion: page._rev,
  set: { value: null },
  reason: `Layout "${layout.title}" was deleted`,
});
// copies: [{ form: "live", locale: null }, { form: "draft", locale: null }]

A Single is rewritten through the same call, named by its slug instead of a collection and an id: { single: "site-settings", field, expectedVersion, set, reason }. Its expectedVersion is the _rev a read of the Single returned, such as nextly.findSingle({ slug: "site-settings" }). A Single's live copy, its drafts, its history and its single.updated event are changed and recorded exactly as an entry's are below.

  • Only from the version you read. expectedVersion is the _rev you read the entry at. If anyone has saved the entry since, the rewrite throws STALE_VERSION (409) and changes nothing. There is no overwrite: read again and decide again.
  • A value, or a function of each copy's own. set: { value } gives every copy the same value. set: { from(current, copy) } is called once per copy with that copy's stored value (a JSON field parsed, a relationship as the id it stores) and returns its new value, so the live page and an author's draft are each transformed from what they hold. Return null to clear the field.
  • Languages. A shared field is rewritten in every language's draft. A translated field is rewritten in one language, locale (the default language when omitted), on its live copy and that language's draft. Its expectedVersion must be a read of that language. Where only that language's live value changes, only that language's version moves, so a read of another language stays current. A shared field or any draft changed moves the document's own version.
  • History. The entry's history gets one field-rewritten event naming the field, each copy changed and your reason. A rewrite made as the system names your plugin. One made with as: "user" names the person, with your plugin beside them. It is never recorded as an overwrite. An editor holding an older version is refused on their next save and sees the conflict.
  • No save hooks. A rewrite runs none of the collection's or fields' before*/after* hooks and no in-transaction handler: they are written for a whole document passing through a save. If a hook derives another field from this one, rewrite that field too. The live change still records the entry.updated event (webhooks), announces the update to ctx.events subscribers once it commits, and revalidates the entry's pages.
  • What it refuses. The id, status, slug and timestamps; a field whose values must be unique (a draft's value is never checked for that); a field stored in tables of its own (a field group, a many-to-many relationship); a password, or a group or repeater holding one or holding a field group; a virtual field; and a value the field's own checks refuse, on any copy. Made with as: "user", it needs the person's permission to update the entry and, where the collection has a publish lifecycle, to publish it, plus every field rule of their own update. The rules judge each new value against the value it replaces: a group or repeater that leaves out or changes a value the person may not change is refused with FORBIDDEN, naming that field in errors[].path (such as card.locked), rather than deleting it.

A bulk job rewrites entries one at a time, each in its own transaction, and retries an entry that moved under it from a fresh read.

Collection transactions

collections.withTransaction runs its work in one transaction, and the *InTransaction methods write inside it. The work receives a PluginCollectionTransaction, an opaque token: pass it as the first argument of createEntryInTransaction, updateEntryInTransaction or deleteEntryInTransaction, which take the same arguments as createEntry, updateEntry and deleteEntry after it, ServiceOpts included. The token carries nothing else, so it cannot run SQL. Any other value passed where the token goes is rejected with VALIDATION_ERROR (logContext.reason is plugin-transaction-token-unknown).

The token works only while the work runs. Kept and passed to an *InTransaction method after the work has settled, it is refused with VALIDATION_ERROR (logContext.reason is plugin-transaction-finished). A write the work started without awaiting is finished inside the transaction before it commits, and if it fails the transaction rolls back and withTransaction rejects with that failure (or with the work's own error, if the work threw). Await each write anyway, so the work sees its result.

await ctx.services.collections.warmLocalizedReadiness("orders");
await ctx.services.collections.withTransaction(async tx => {
  const order = await ctx.services.collections.createEntryInTransaction(
    tx,
    "orders",
    { total: 40 },
    { as: "user", user: ctx.user ?? undefined }
  );
  await ctx.services.collections.updateEntryInTransaction(
    tx,
    "orders",
    order.id,
    { status: "placed" },
    { as: "user", user: ctx.user ?? undefined }
  );
});

The *InTransaction methods resolve ServiceOpts exactly as the access methods above do, so a transaction is no way around the access check: an overrideAccess key or a caller's roles passed to them are not read, and the caller's roles are looked up. They return the row itself (deleteEntryInTransaction returns nothing) rather than the { message, item, warnings? } envelope.

getCollection reads a collection's record through the pool, so inside a transaction on a pool of one connection, the usual serverless setting, it waits for the connection the transaction holds until the pool gives up. getCollectionInTransaction(tx, slug) (@experimental) answers the same record on the transaction's own connection, from the work's tx or an in-transaction handler's transaction. Like getCollection, it asks nothing of the caller's access and is refused with NOT_FOUND for a collection there is no record of. It takes no lock: use holdCollectionInTransaction where a write must not outlive the collection.

ctx.hooks.onInTransaction("*", async write => {
  const record = await ctx.services.collections.getCollectionInTransaction(
    write.transaction,
    write.collection
  );
  // ...
});

listEntries reads through the pool too, and waits the same way. listEntriesInTransaction(tx, slug, options, opts) (@experimental) is listEntries on the transaction's own connection: the same options and ServiceOpts, the same access check and read hooks, and the same answer, so it sees what the transaction wrote. Under as: "user" the caller's roles are read on the transaction too. The page's rows are read with a shared lock on PostgreSQL and MySQL, held until the transaction ends. It grants nothing listEntries does not.

ctx.hooks.onInTransaction("*", async write => {
  const { data } = await ctx.services.collections.listEntriesInTransaction(
    write.transaction,
    "posts",
    { where: { id: { in: ["p1", "p2"] } }, select: { id: true, slug: true } }
  );
  // ...
});

ctx.services.users may create and update accounts, but not decide who administers the site. It refuses, with NextlyError code FORBIDDEN, to create an install's first account (core makes that one super-admin), to give a role that reaches super-admin (directly or by inheritance) on create or update, and to change the password, email, activation, email verification or roles of an account that reaches super-admin, or to delete one. An address it marks verified is recorded as verified by plugin.

It also refuses, with FORBIDDEN and nothing written, an update that would leave an account active, verified and without a password. That is the account core makes for a person another system has verified, and core makes it only when one of the app's login plugins hands it a sign-in. A create cannot make one: it requires a password, and on an install that already has an account a create without one is refused with VALIDATION_ERROR before this rule is reached (on an empty install every plugin create is refused with FORBIDDEN first, as above). The refusal is judged on the account a write leaves, and only for a write that changes its activation, verification or address. A stored password counts as one when it is a hash core made, or, where the app brings its own passwordHasher, one that hasher recognises (any stored value, if it declares no isHash). An account core made this way still takes your plugin's other edits, and can be deactivated or given a password, but a plugin cannot verify an active account that has no password (re-verifying one core made included), activate a verified one that has none, reactivate one core made, or move one core made to another address unless the same write gives it a password. An active account with no password that is not verified, such as an imported account whose owner sets a password by reset, stays allowed.

Reading your own collections without site hooks

A plugin's bookkeeping, such as a usage index or a backfill cursor, is read to decide something. A site hook that scopes every read to a tenant, retargets a read by id, or rewrites the document would make that answer wrong while it still looks exact. { as: "system" } doesn't help, because it skips only the access check.

ctx.services.ownCollections reads only the collections your plugin declared, with no configured read hook shaping the read. It is @experimental.

const inUse = await ctx.services.ownCollections.count(
  ctx.self.collections.usageIndex,
  { where: { component: { equals: componentId } } }
);

What it skips:

  • the collection's beforeOperation, beforeRead and afterRead hooks, including * global hooks and every plugin's own, yours too;
  • stored hooks configured in the admin;
  • field hooks set in config;
  • the collections.listQuery filter.

What it keeps (what a field's type does to make a stored value readable, none of which is a hook):

  • JSON decoding;
  • timestamp fields in their API form (createdAt);
  • the redaction of server-only values, such as password hashes and the owner column;
  • the rich-text output format and select;
  • decryption, where a field type decrypts its value (no core field type does today).

The rules:

  • It offers listEntries, findEntryById, count and group (and, inside a transaction, the reads below), and runs as the system only, never as a person, even inside a person's request. Its options carry only context, locale and fallbackLocale.
  • Any other collection is refused before anything is read. That includes another plugin's, the app's, and the collections of a plugin you depend on (dependsOn). Contrast ctx.db, which lets a dependent plugin read the owner's tables.
  • It only reads. Writes keep every hook.
  • A related document expanded into the result (depth 1 or more) keeps its own collection's hooks, so the waiver never travels to a row your plugin didn't declare.

Never return what ownCollections reads to a person, in a route response or anywhere else. A site's read hooks may be what keeps one tenant's rows from another, and this read skips them. Use it to decide something in your plugin's own code; read through ctx.services.collections for anything a person sees.

Reading your own content inside a transaction

A handler that runs inside a write's transaction (ctx.hooks.onInTransaction), or work inside collections.withTransaction, cannot read through listEntries or findEntryById: they take a connection from the pool. That connection cannot see what the transaction wrote, and on a pool of one connection, the usual serverless setting, it never comes free: the transaction holds it until the read returns, so the read waits until the pool gives up.

Three @experimental reads run on the transaction's own connection instead. Each takes the transaction token first: the tx that withTransaction hands its work, or the handler's transaction.

  • listEntriesInTransaction(tx, slug, options?, opts?) takes the same options as listEntries and gives the same answer.
  • findEntryByIdInTransaction(tx, slug, id, opts?) gives the same answer as findEntryById.
  • getSingleInTransaction(tx, slug, opts?) reads a Single your plugin declared, as stored. None of the Single's read hooks run (beforeOperation, beforeRead, afterRead, and its fields' afterRead). A Single with no stored document answers the default document, and nothing is written.
ctx.hooks.onInTransaction(ctx.self.collections.claims, async write => {
  const { data } = await ctx.services.ownCollections.listEntriesInTransaction(
    write.transaction,
    ctx.self.collections.claims,
    {
      where: { address: { equals: write.data?.address } },
      pagination: { limit: 50 },
    }
  );
  // ...decide from rows that include this write's own, uncommitted one
});

They follow the rules above: as the system, your own collections and Singles only, and a settled token is refused, both before anything is read. On PostgreSQL and MySQL the rows they read are locked FOR SHARE until the transaction ends. A locked read sees the latest committed row, whatever the transaction's isolation level, and a write to that row from elsewhere waits for your transaction. A list's pagination.total is a count, which takes no lock, so rows can still be added beside your page: page with limit, and stop on a page shorter than the limit rather than on the total. SQLite has one connection and one writer, so there is nothing to lock.

When the read goes on to write the rows it read, pass { lock: "update" } as the last argument of listEntriesInTransaction or findEntryByIdInTransaction. The rows are then locked FOR UPDATE, so a second transaction doing the same waits for yours, rather than both holding a shared lock that the other's write then waits on, which the database ends by refusing one of them.

When your transaction already holds a lock of its own, such as a lock row each of your writes updates first, and reads rows another writer may be updating, pass { lock: "none" } (@experimental) to any of these reads, getSingleInTransaction included. The read is then a plain read on your transaction's connection: no FOR SHARE or FOR UPDATE, so it waits for no other writer and holds nothing it read. A locking read would wait for that writer while the writer waits for your lock, and the database would end the wait by refusing one of you as a deadlock. Under READ COMMITTED, PostgreSQL's default, the plain read sees the latest committed rows. Under REPEATABLE READ, MySQL's default, it answers from your transaction's snapshot, which can be older than a commit your lock was meant to wait for: guard against that yourself. On SQLite the three read alike.

Reading host content that holds your field type

A plugin that registers a field type (contributes.fieldTypes) may need to read the host content that uses it, inside the same transaction: the site's own collections and Singles, which it did not declare. Three more @experimental reads do that, with the same arguments, answers, locking and lock option as the reads above:

  • listHostEntriesInTransaction(tx, slug, options?, opts?)
  • findHostEntryByIdInTransaction(tx, slug, id, opts?)
  • getHostSingleInTransaction(tx, slug, opts?)

A collection or Single is readable this way only when it holds a field of a type your plugin registered, at any depth: at the top level, inside groups and repeaters, or inside a component it uses. That is decided at each call, from the schema as it stands on the transaction, so a collection the Schema Builder created or changed after your plugin started is judged as it is now. Anything else is refused with INVALID_INPUT (logContext.reason is host-collection-read-not-eligible or host-single-read-not-eligible) before its rows are read. They run as the system and skip the content's read hooks, for that one collection or Single and that one call; a related row keeps its own hooks. The same warning applies: never return what they read to a person.

To find that content without naming it first, listHostTypesInTransaction(tx) (@experimental) answers { collections, singles }: each collection and Single holding a field of a type your plugin registered, as services.collections.listCollections and services.singles.list list them, judged by the same rule, so a host read of any slug it lists is not refused on the same transaction. Your own collections and Singles are judged like any other. Those two listings take a pooled connection, which inside a transaction on a pool of one waits for the connection the transaction holds; this one reads on the transaction's connection, in a few statements whatever the number of collections and Singles: the collections, the Singles, and every component's fields when a schema names a component. Each collection and Single is judged by the schema read in the same statement as itself. A plugin that registered no field type gets both lists empty.

await ctx.services.collections.withTransaction(async tx => {
  const { collections, singles } =
    await ctx.services.ownCollections.listHostTypesInTransaction(tx);
  for (const collection of collections) {
    const page = await ctx.services.ownCollections.listHostEntriesInTransaction(
      tx,
      collection.name,
      { pagination: { limit: 50 } }
    );
    // ...
  }
});

When to drop to ctx.db

ctx.db is the @experimental database surface — unmanaged: it bypasses validation, hooks, RBAC, and events. Reach for it only for things the services layer doesn't cover yet (aggregations beyond count), or for the tables your plugin declared itself. If you find yourself needing it often, that's a signal worth raising — the goal is that most plugins never touch it.

It comes in two layers:

  • ctx.db is typed and owner-checked: select, insert, insertReturning, update, delete, table, query and transaction, over the tables your plugin declared and its dependencies' tables. It behaves the same on every dialect, and a table your plugin may not reach is refused before a query is built, and checked again when the query runs: a ctx.db.query.<table> entry or a select, update or delete builder kept across a schema reload cannot reach a table your plugin no longer may. Your dependencies are read from the config in force too, so a reload that drops one from dependsOn takes its tables away without a restart. Reflection reaches no further than a call: ctx.db.query hands out only the checked entry of a table you may reach, and refuses an assignment. A select builder is immutable: where, orderBy, limit and offset each return a new builder and leave the one they were called on as it was, and first() runs the query without changing its builder, so one base builder can be narrowed several ways. See Tables of your own. A counter is ctx.db.update(table, { hits: increment(1) }).where(...), with increment from @nextlyhq/plugin-sdk/db (@experimental): the database adds to the stored value in that one statement (hits = hits + 1), so updates made at once all count, and the number it resolves to says whether a row matched. It takes a numeric column (integer, smallint, bigint, real, double, decimal) and refuses any other with a NextlyError, code VALIDATION_ERROR; it is a value update reads, not SQL. Inside a transaction, tx.select(table).where(...).lock("update") reads the rows locked until the transaction ends (@experimental): "update" (FOR UPDATE) keeps any other transaction from changing or locking them, "share" (FOR SHARE) only from changing them. Either reads the latest committed rows, which on MySQL a plain read inside a transaction does not: it answers from the snapshot the transaction's first read took. SQLite runs one writer at a time, so there it reads as a plain read does. count() ignores it, and a snapshot transaction refuses it with a NextlyError, code INVALID_INPUT.
  • ctx.db.raw is Drizzle's fluent builder for the configured dialect — select, insert, update, delete — plus transaction, with no owner check, and you own dialect portability. It has no execute, run or query. If your plugin declares capabilities.db.rawSql and the app lists it in db: { rawSqlPlugins: [...] }, ctx.db.raw is the live Drizzle instance instead, execute and run included. A plugin that declares rawSql without being listed stops the boot. The grant is decided once, when the boot resolves the plugin list: setting capabilities.db.rawSql on a definition afterwards grants nothing. See Raw SQL.

Both transactions commit the work as one unit and roll it back if the work throws, on every dialect. Inside one, write through tx:

  • ctx.db.transaction(async tx => { ... }) hands tx the same typed surface, bound to the transaction's connection. tx has no transaction in its type, and calling one anyway rejects with a NextlyError, code INVALID_INPUT (logContext.reason is nested-plugin-transaction), rather than opening a second transaction on another connection. Do the nested work in the same callback, through tx.
  • ctx.db.raw.transaction(async tx => { ... }) hands tx the fluent builder, without a nested transaction. With rawSql listed, tx is the live handle and its transaction nests as a savepoint.

tx works only while the callback runs. Kept and called after the callback has settled, it is refused with VALIDATION_ERROR (logContext.reason is plugin-transaction-finished) rather than running outside the transaction. So is a method taken off it while the callback ran, such as const insert = tx.insert, when it is called after.

In ctx.db.transaction, a statement the callback started without awaiting is finished inside the transaction before it commits; if one fails, the transaction rolls back and rejects with that failure (or with the callback's own error, if the callback threw). In ctx.db.raw.transaction, awaiting each Drizzle statement before the callback returns is yours to do: a kept tx is refused, but a Drizzle builder made inside the callback carries the transaction's connection with it, so one awaited after the callback has settled runs outside the transaction.

On PostgreSQL a statement that fails inside a transaction aborts it: every later statement is refused, and the transaction can only roll back. So a statement whose failure your callback catches still takes the transaction down with it. ctx.db.transaction then rejects with a DatabaseError (code 25P02) rather than resolving with nothing kept. ctx.db.raw.transaction is Drizzle's own transaction and does not: it resolves although nothing was kept, so in it, let a failed statement reject the callback rather than catching it. MySQL and SQLite undo only the failed statement and let the transaction go on, except that MySQL undoes the whole transaction on a deadlock. A statement that may fail, and that the rest of the work should not depend on, belongs outside the transaction.

Another service called inside a transaction runs on its own connection on PostgreSQL and MySQL, outside the transaction, and commits on its own.

ctx.settings.set is refused inside a transaction, on every dialect, with an error that says so: write the setting after the transaction has finished.

On SQLite the transaction holds the database's only connection until it ends. A service called inside joins it as a savepoint, and its rows roll back with it. What a service does after its own write waits until your transaction commits: collection hooks (afterCreate, afterUpdate, afterDelete), field afterChange hooks, events such as user.created or media.uploaded, cache revalidation and webhook delivery run once, before ctx.db.transaction resolves, and never run if it rolls back. Inside such a transaction an after-hook's error is logged rather than failing the call, and a value a field afterChange hook or a Single's afterUpdate hook returns does not reshape the service's response. A media delete (ctx.services.media.delete or bulkDelete) called inside it is refused with 409 CONFLICT, so stored files are never removed for a delete that rolls back: delete media after the transaction.

Statements from other requests wait for the transaction or run inside it. Core's security writes — sign-out, the refresh-token theft response, failed-attempt and lockout counts, role assignment and removal, API-key revocation and audit entries — queue behind it instead, so its rollback cannot undo them. Keep it short, and never await network I/O such as ctx.fetch inside it.

Nested transactions on SQLite run one at a time, in the order they are started. A nested transaction must never wait for one started after it in the same transaction, for example through a memoised or cached promise that a later sibling created. Neither settles, and the connection stays inside your open transaction: every later transaction waits, and other requests' writes land in it without ever committing, so a restart loses them. Start shared work before the transactions that wait on it, or outside the transaction.

Relational queries are on the typed surface, ctx.db.query.<table>.findMany({ with }), and reach only the tables ctx.db may reach. ctx.db.raw has no query namespace.

capabilities.db.rawSql and the app's db.rawSqlPlugins listing are a grant a reviewer can read, not an enforced boundary: plugins run as trusted code.

See also: Permissions · HTTP routes.

Forgetting what you sent

When your plugin deletes a record whose data its emails carried (a form submission, say), ctx.services.email.forgetSends forgets those emails with it. Hand it the ids queue and queueWithTemplate answered and the idempotency keys the sends carried:

  • each of those queued emails still waiting, or failed and retryable, is cancelled, and every one of them has its message and recipients cleared; one already with the provider finishes as it is;
  • every delivery record of those sends is erased: its address and key digests go, the row stays.

A send is found by its key. When a person named on a send has already been deleted, their deletion cleared that key from every record of the send, so the records of the send's other recipients (a CC, say) are no longer found by it: they are those people's records, erased with their own deletion.

Only your plugin's own emails and keys are touched. Pass tx, the handle a ctx.db.transaction callback or an in-transaction handler received, to commit it with your deletion; without one it runs in a transaction of its own and is refused inside an open one.

ctx.hooks.onInTransaction("orders", async write => {
  if (write.operation !== "delete") return;
  await ctx.services.email.forgetSends(
    { queuedIds: ["0b5c…"], idempotencyKeys: [`order:${write.id}`] },
    { tx: write.db }
  );
});

Knowing what became of what you sent

A plugin that keeps its own record of each email it queued (a form showing, on a submission, who its notification reached) is told of every change of its own queued emails, inside the transaction that makes it. What your handler writes through db, or through the collection services' *InTransaction methods with transaction, commits or rolls back with the change, so your record never falls behind the send or runs ahead of it. A handler that throws undoes the change, and the next attempt makes it again (an attempt with the same key never sends twice), so write as an upsert keyed by the queued email's id and each recipient's digest.

Each change (QueuedEmailChange, @experimental) has the queued email's id, the key you queued it with, the attempt and its time, and a state:

  • sending: an attempt is starting; with cancelRequested, a cancel reached the attempt already with the provider, which ends sent if the provider takes it and cancelled if it fails;
  • retrying: the attempt failed in a way a retry can help (failure says why), and another follows;
  • sent, failed, or cancelled with cancel: by a person (their user id), by your own forgetSends (sender), or by a request made during an attempt (request).

Where a provider was asked, recipients lists every recipient the send went to after email.beforeSend filters ran, each with its line (to, cc, bcc), what became of it (accepted, refused, unknown, or skipped when you excluded it), a masked hint for a screen (j•••@example.com) and your plugin's digest of it. No address is ever handed over. The digest is what ctx.services.email.recipientDigest(address) gives: keyed by your plugin's own key, it stays the same across rotations of the install's secret. Take the first one outside a transaction.

ctx.services.email.onQueuedEmailChange(async (change, { transaction }) => {
  for (const recipient of change.recipients ?? []) {
    await ctx.services.collections.createEntryInTransaction(
      transaction,
      "my-send-outcomes",
      { queuedId: change.queuedId, state: change.state, ...recipient }
    );
  }
});

An erasure cancels queued email in the erasure's own transaction and does not call your handler: a person's erasure never waits on a plugin. Read where your emails stand with ctx.services.email.readQueued(ids) (at most 500): each of your own is waiting, retrying, sending, sent, failed or cancelled, with its attempts and whether its message is still held; an id that is not yours is left out. Use it to say a send is still in progress before offering to send it again.

To send an email again to the recipients who did not get it, pass excludeRecipients, the digests of those who did, on queue, queueWithTemplate, send or sendWithTemplate. They are compared with the recipients email.beforeSend filters return, so a recipient a filter adds is left out too. When no to is left, each remaining copy gets a message of its own with itself as the only to, so a blind copy is never shown to another. When nobody is left, nothing is sent. It cannot be combined with person.

People cancel a queued email with the Direct API's nextly.email.cancelQueued({ id }), which asks manage-email-deliveries of a checked call (see Direct API).

Showing an image at a known width

A plugin that draws images can ask for a resized copy rather than sending the original. ctx.services.media.copyOf(source, width) (@experimental) takes a media item as { id }, or an address as { url }, and the width the image is shown at. It answers the copy's url and the allowed width it snapped to, or null when the image is to be used as it is. See Resized copies for the widths, formats and storages.

MEDIA_COPY_WIDTHS and nearestMediaCopyWidth come from @nextlyhq/plugin-sdk, so a srcset can be built from the same widths the server keeps:

import { MEDIA_COPY_WIDTHS, type PluginContext } from "@nextlyhq/plugin-sdk";

/** A `srcset` for an image shown `shown` pixels wide, up to twice that. */
export async function srcsetOf(
  ctx: PluginContext,
  mediaId: string,
  shown: number
): Promise<string> {
  const wanted = MEDIA_COPY_WIDTHS.filter(width => width <= shown * 2);
  const copies = await Promise.all(
    wanted.map(width => ctx.services.media.copyOf({ id: mediaId }, width))
  );
  return copies
    .flatMap(copy => (copy === null ? [] : [`${copy.url} ${copy.width}w`]))
    .join(", ");
}

Freeing media nothing uses

A plugin that uploads files for its own records can free them once those records are gone. ctx.services.media.isInUse(mediaId) (@experimental) answers whether anything still uses an item: a document's field, as the usage record has it, or an avatar or logo that keeps its address. It is the same condition the media library's Unused view applies, asked of one item.

It answers true whenever that cannot be known yet: before nextly migrate has made the usage table, while the record is unbuilt for content written before it existed (nextly media reindex-usage), or for an id no item has. So a plugin that deletes only what reads as unused never deletes on a guess. Your plugin's own records are not in the usage record: check them yourself before asking. Delete after the transaction that removed your records, since a media delete is refused inside one.

for (const mediaId of fileIdsOfDeletedRecord) {
  if (await stillReferencedByMyRecords(mediaId)) continue;
  if (await ctx.services.media.isInUse(mediaId)) continue;
  await ctx.services.media.delete(mediaId);
}