Plugin Author Guide
Build a Nextly plugin — the lifecycle, the plugin context, and the scaffold → dev → test → publish loop.
Alpha (
0.x) — pin your versions.The plugin SDK is alpha: its
@publicsurface becomes semver-protected at 1.0 (see API stability). Build against@nextlyhq/plugin-sdk— it is the stability boundary — and until then pin exactnextly/@nextlyhq/plugin-sdkversions.
A plugin extends Nextly with new collections, hooks, events, routes, permissions, and admin UI — without modifying core. This guide is the overview; deeper topics each have their own page:
- Lifecycle, dependencies & order —
setup/init/destroy, load order,dependsOn, version compat,enabled - Data access —
ctx.services, queries, bulk ops,{ as: "system" } - Permissions — declare-but-never-grant, route gating,
useCan/<Can> - HTTP routes —
contributes.routes, secure-by-default, middleware - Admin UI — menu, pages, view overrides, placement
- Schema & data lifecycle — collections,
extend, relations, provenance, uninstall - Testing · API stability · Publishing & distribution
Scaffold a plugin
npm create nextly-app -- --template pluginThis generates a publishable package whose plugin code lives in src/ plus an embedded dev/ playground — a minimal Nextly app on SQLite with hot-reload that registers your plugin so you can exercise it in a real admin. dev/ is never published (only dist/ ships).
my-plugin/
├── src/ # your plugin (published as dist/)
│ ├── index.ts
│ ├── plugin.ts # definePlugin(...)
│ ├── collections/
│ └── admin/
├── dev/ # local playground — NOT published
│ ├── nextly.config.ts # registers your plugin
│ ├── next.config.ts # source-mode HMR for src/
│ └── instrumentation.ts
└── package.json # files: ["dist"]; nextly-plugin keywordThe plugin object
Author with definePlugin from @nextlyhq/plugin-sdk:
import { definePlugin } from "@nextlyhq/plugin-sdk";
type MyPluginOptions = { greeting?: string };
export const myPlugin = (opts: MyPluginOptions = {}) =>
definePlugin({
name: "@acme/nextly-plugin-greetings",
version: "0.1.0",
nextly: ">=0.0.2-alpha.63", // core-compatibility range, boot-checked
dependsOn: {}, // required plugin deps → version range
enabled: true, // false skips behavior but keeps schema
contributes: {
/* declarative nouns — see below */
},
setup(config) {
// a copy of the plain settings and plugin definitions, no live handles
return config;
}, // escape hatch — all setups run before any init
init(ctx) {
/* runtime wiring */
},
destroy(ctx) {
/* teardown on shutdown, re-registration and test teardown */
},
});Give the plugin its package name. The name app is reserved, in any letter case, because the
site's own permissions are stored under it: a plugin named app is refused at startup and by
every CLI command.
Choosing the nextly range
The floor names the release that introduced the newest core API your plugin actually calls — not the version you happened to develop against, and not the latest release.
Get it too low and the failure is confusing: your plugin boots against a core that lacks the API, the import resolves to nothing, and the crash names a symbol rather than a version. Too high, and installs that would have worked are refused.
There is one case that catches people out. If the API you need is landing in the same release as your plugin — you added it to core yourself, or you are building inside the Nextly monorepo — then the version to name does not exist yet. Writing the next one is a guess about a release that has not happened, and it makes your plugin unusable in the source tree, where core carries the current version: every boot fails compatibility before a single test runs.
Where your package and core version together, say so directly instead:
import { version } from "../package.json";
definePlugin({
name: "@acme/nextly-plugin-greetings",
version: "0.1.0",
// Released in lockstep with core, so a core at least as new as this build is
// exactly the compatibility that is meant — and it stays true after every
// release without being edited.
nextly: `>=${version}`,
// …
});That only applies where the two genuinely ship together. A plugin released on its own schedule should name the real floor, and leave it alone until it calls something newer.
contributes (declarative)
contributes is data the host can read without running your plugin (so the admin and codegen can reason about it):
collections/singles/components— new, plugin-owned schema entities.extend— add fields to existing entities by slug.permissions— custom (non-CRUD) permissions; CRUD is auto-seeded per collection/single.events— custom event names you may emit.routes— HTTP endpoints, namespaced under/plugins/<name>/…beneath wherever your app mounts the Nextly handler (/admin/apiin a scaffolded project), secure by default.admin— menu, pages, settings, and per-collection view overrides (referenced by string component path).
Lifecycle
contributes → setup → init → destroy. All plugins' setups run before any init. Load order is a topological sort over dependsOn (array order breaks ties). A missing/incompatible/cyclic dependency is a fail-fast boot error (see the error reference).
The plugin context (ctx)
init(ctx) and destroy(ctx) receive:
| Field | Use |
|---|---|
ctx.services | Managed data access — secure by default (acts as the ambient user, RBAC on). Pass { as: "system" } to elevate. Validation/hooks/events always run. |
ctx.db | Typed, owner-checked access to your declared tables — unmanaged (no validation, hooks or events). ctx.db.raw is the Drizzle builder escape hatch; execute/run need capabilities.db.rawSql and the app's db.rawSqlPlugins listing. |
ctx.dialect | The database this installation runs on (@experimental). |
ctx.hooks | Hooks — can modify or abort an operation before it writes, or write inside its transaction (onInTransaction). |
ctx.events | Post-commit event bus — observe-only, best-effort (may be dropped). React/notify here. |
ctx.filters / ctx.actions | Typed seams to transform values / run ordered side-effects. |
ctx.self | Your entities' resolved slugs after any host .rename(). Always reference your own entities through this. |
ctx.logger | Structured logging. |
ctx.config | A PluginConfig: a frozen copy of the plain configuration values. No live handle (adapter, logger, hook registry, storage, rate limiter) and no email provider credentials; plugins lists summaries, not definitions. Reach the database through ctx.db and log through ctx.logger. |
ctx.nextlyVersion | The running core version (feature detection). |
Hooks vs events: need to change or block an operation → use a hook; need to react after it commits → use an event.
When each hook runs
A write offers five timings, in this order:
| When | What runs | How often |
|---|---|---|
| Before the write | beforeOperation, beforeCreate / beforeUpdate / beforeDelete, beforeChange | once |
| In the transaction | ctx.hooks.onInTransaction handlers (@experimental) | once per attempt, so possibly more than once |
| At the commit | the collection events: collection.<slug>.created, .updated and .deleted | once |
| After the commit | afterCreate / afterUpdate / afterDelete | once |
| After | field afterChange hooks | once |
A collection event announces the commit, so it comes before the after-hooks.
Before this release it came after them: a listener that relied on the
after-hooks having run should do its work in an after* hook instead.
Some writes run their after-hooks inline, inside a transaction, before it
commits: one made inside a transaction its caller opened
(createEntryInTransaction, updateEntryInTransaction,
deleteEntryInTransaction), and each entry of the batch writes createEntries,
updateEntries and deleteEntries. There the after-hooks come first, and the
collection event is delivered once the outermost transaction commits, and never
if it rolls back. Before this release these writes sent no collection event.
An in-transaction handler runs last inside the write's own transaction: after the entry, its field groups, its version and its outbox event are written, and before the commit. It is handed the write and your db, bound to that transaction, so a row you write there commits or rolls back with the entry:
init(ctx) {
ctx.hooks.onInTransaction(ctx.self.collections.orders, async ({ operation, id, db }) => {
if (operation === "create") await db.insert(orderLedger, { orderId: id });
});
}- It runs for create, update and delete on collections, for publishing or withdrawing every language, and for a Single's update and publish. Register a Single's handler as
single:<slug>; a Single is only ever updated."*"registers for every collection and Single. - It runs once per entry in a batch, and even when the write skips its hooks: what it writes is integrity, not a reaction.
- Throwing aborts the write and nothing of it is kept. The caller gets the error's own status: throw a
NextlyError(NextlyError.validation(...),NextlyError.forbidden(...)) to answer with one; any other error answers 500. In a batch that shares one transaction, a handler that throws aborts the whole batch, whateverstopOnErrorsays. - It may run more than once. When the write loses a version-conflict race, the attempt is rolled back and tried again, and your handler runs again with it; only the attempt that commits keeps its writes. So write only through the
dbyou are handed. A network call, an email or a write through the outerctx.dbis not undone with a discarded attempt: in development Nextly warns, once per plugin, when a handler makes an outbound HTTP call. Do that work after the commit, in anafter*hook or an event. - Keep it short: the entry's row stays locked while it runs.
readStored(fieldType, target)reads a stored value of a field type your plugin contributes, on the same transaction, with the scope a field type's validator has: so a rule your field type judges against other stored values can be judged again on the value finally stored. A target naming no language reads the app's default language.fieldPaths(fieldType)lists the written document's fields of that type, at the top level and through named groups. A collection write that runs in-transaction handlers reads committed on every dialect, so a handler that serializes writes by locking a row of its own table reads what committed before it took the lock. A Single's write, and a write inside a transaction its caller opened, read at that transaction's isolation.
Taking part in deleting a collection
A plugin that keeps rows naming a collection by slug, in a collection or table of its own,
can have them go with the collection. ctx.hooks.onCollectionDelete (@experimental)
takes two optional handlers:
init(ctx) {
const designs = ctx.self.collections.designs;
const naming = (slug: string) => ({ where: { target: { equals: slug } } });
ctx.hooks.onCollectionDelete({
// Listed in the admin's delete dialog, under your plugin's name, before the confirm.
impact: async slug => {
const { data } = await ctx.services.ownCollections.listEntries(designs, naming(slug));
return data.map(row => ({ label: String(row.title), kind: "design" }));
},
// Run inside the delete's transaction, before the collection is removed.
inTransaction: async ({ slug, transaction }) => {
const { data } = await ctx.services.ownCollections.listEntriesInTransaction(
transaction, designs, naming(slug), { lock: "update" }
);
for (const row of data) {
await ctx.services.collections.deleteEntryInTransaction(
transaction, designs, String(row.id), {}
);
}
},
});
}impactis asked for each collection the delete dialog is about to delete, as the admin opens it (GET /api/collections/schema/<slug>/delete-impact). It must only read. It answers{ label, kind }items; anything else fails the dialog's check and names your plugin in the log.inTransactionruns for each collection deleted, the Schema Builder's delete and a bulk delete of several alike, inside the delete's transaction and before the collection's field-group values, translations, table and registry row are removed.transactionis a token for the*InTransactionmethods ofctx.services.collectionsandctx.services.ownCollections, refused once your handler settles.- Throwing refuses the delete, and nothing of it is kept: your handler runs before the delete's first table drop, so this holds on MySQL too. On MySQL a failure after that point (a table drop, the registry row's removal) can leave what your handler removed gone while the collection stays registered, because MySQL commits each table drop with everything before it; deleting the collection again finishes it.
- Both are asked about every collection deleted, your own among them: decide in the handler which you hold anything for.
- A write of yours that names a collection and must not outlive it (a row your
inTransactionwould remove) can still commit after that handler read what to remove. Close the gap by holding the collection inside the write's transaction withctx.services.collections.holdCollectionInTransaction(tx, slug)(@experimental), and refuse the write when it answersfalse: the delete holds the collection's registry row for update before your handler runs, so the write either commits first and is removed with the collection, or waits and is told the collection is gone. On MySQL, where a table drop commits the delete's row locks, both also take a named lock on the collection, which the delete holds until its registry row is removed. - The same holds for a row of yours that names one ENTRY and must not outlive it, such as
one an
onInTransactionhandler on the entry's deletes removes. Hold the entry inside the write's transaction withctx.services.collections.holdEntryInTransaction(tx, slug, id)(@experimental), and refuse the write when it answersfalse: a delete locks the entry's row for update before removing it and runs its in-transaction handlers after, so the write either commits first and the handlers see it, or waits and is told the entry is gone. It holds the entry's collection first, asholdCollectionInTransactiondoes, so a delete of the whole collection, which locks the registry row rather than its entries' rows, takes turns with the write the same way and itsonCollectionDeletehandlers see the row. Hold it before you write the row where you can, as an in-transaction handler on your own collection's creates runs after the row is written: on MySQL a delete reading that row meanwhile can deadlock with the hold, and the database then refuses one of the two.
Never hardcode your own slugs in init. Use ctx.self so your plugin keeps working when an integrator renames an entity:
init(ctx) {
ctx.hooks.on("afterCreate", ctx.self.collections.submissions, sendEmail);
ctx.events.on(`collection.${ctx.self.collections.submissions}.created`, notify);
}The dev loop
pnpm install
pnpm dev # runs the dev/ playground (next dev) → open /adminEditing files under src/ hot-reloads the playground (the dev/next.config.ts transpiles your plugin source). A hot reload re-runs neither init() nor destroy(), so restart pnpm dev after changing either. destroy() runs on shutdown and before services register again: clean up subscriptions and timers there.
HMR gotcha: Nextly's registries (hooks, events, filters) survive hot-reload because they live on
globalThis. If you keep state in a module-scoped singleton, it will be recreated on every reload and your subscriptions lost. Register throughctx.hooks/ctx.events/ctx.filtersinstead.
Test
import { createTestNextly } from "@nextlyhq/plugin-sdk/testing";
import { myPlugin } from "../src";
const t = await createTestNextly({
plugins: [myPlugin()],
collections: myPlugin().contributes.collections,
});
// drive t.nextly / assert t.hooks, t.events, inspect t.adapter …
await t.destroy();createTestNextly boots a real Nextly on in-memory SQLite and runs your full lifecycle.
To check your plugin against a real database, pass dialect. Each boot gets its own database, created and dropped by destroy(), so runs never contaminate each other:
import {
createTestNextly,
getConfiguredTestDialects,
} from "@nextlyhq/plugin-sdk/testing";
import { describe, it } from "vitest";
// "sqlite" is always included; the others are included when TEST_POSTGRES_URL /
// TEST_MYSQL_URL point at a server you are willing to create databases on.
// Configured, not probed: a URL you set but cannot reach fails rather than
// skipping, which is usually what you want from a broken environment.
for (const dialect of getConfiguredTestDialects()) {
describe(`myPlugin (${dialect})`, () => {
it("works", async () => {
const t = await createTestNextly({ dialect, plugins: [myPlugin()] });
// …
await t.destroy();
});
});
}Worth doing if your plugin contributes collections or touches the database directly: column types, default expressions, and JSON handling differ between dialects in ways SQLite alone will not reveal.
Type safety (codegen)
Run nextly generate:types in the consuming app to narrow CollectionSlug, PermissionSlug, and EventName to the real, installed values — including your plugin's. When a plugin contributes admin components, the same command emits a plugin-admin-imports.generated.ts import map so those React components load with no manual host imports.
Publish
Build (tsdown), publish to npm, and add the nextly-plugin keyword to package.json so it's discoverable. Declare an honest nextly range. See the API reference for the full public surface and the error reference for boot-error meanings.
Stability
The public surface (definePlugin/contributes/lifecycle, ctx.services, contributes.routes, contributes.admin, ctx.events + event names, HookContext, and @nextlyhq/plugin-sdk/testing) is now @public — semver-protected, so breaking it requires a Nextly major. Some surfaces are still @experimental (ctx.db and its ctx.db.raw escape hatch, ctx.hooks registration, filters/actions, secret(), useCan/<Can>, admin widgets) and may change. The full ledger is on the API stability page. Pin versions while we are pre-1.0.