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

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 (D35)

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.

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
emailPluginEmailServicesend, sendWithTemplate, 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 (D56)

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.

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.

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 passes its own passwordHasher to getNextly, whatever that hasher stored. 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.

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.

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 (D56) 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.
  • 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.