Plugin API Reference
The public plugin surface re-exported by @nextlyhq/plugin-sdk.
Alpha (
0.x) — pin your versions.@nextlyhq/plugin-sdkis the stability boundary — if it isn't exported there, it isn't public. Most of this surface is now@public(semver-protected); some is still@experimental. See API stability for the exact ledger.
Entry points
| Import | Surface | React? |
|---|---|---|
@nextlyhq/plugin-sdk | definePlugin, contributes/ctx/hook/event/filter types, PermissionSlug/EventName, secret() | no |
@nextlyhq/plugin-sdk/testing | createTestNextly | no |
@nextlyhq/plugin-sdk/client | useCan, <Can> | yes (optional peer) |
@nextlyhq/plugin-sdk/admin | registerComponent, registerComponents, registerKnownPlugin (deprecated), ChallengeViewProps, ChallengeResolveResult | yes (optional peer) |
@nextlyhq/plugin-sdk/routing | slugToStaticParam | no |
@nextlyhq/plugin-sdk/db | Drizzle query operators (eq, and, inArray, …) and increment for ctx.db.update; sql is not among them — a declaration a reviewer reads, not a boundary, since a plugin can bundle its own | no |
@nextlyhq/plugin-sdk/widgets | WidgetProps, WidgetData, WidgetRenderSize, WidgetResult, WidgetResultField — types only, no runtime | no |
definePlugin(def): PluginDefinition
interface PluginDefinition {
name: string;
version: string;
nextly: string; // core-compat range (boot-checked, may span majors)
dependsOn?: Record<string, string>; // required deps → version range
optionalDependsOn?: Record<string, string>; // enhance-if-present
enabled?: boolean; // default true; false = skip behavior, keep schema
contributes?: PluginContributions;
capabilities?: PluginCapabilities; // { net?: { outbound }, db?: { rawSql }, secrets?, auth?: { login } }
provides?: string[]; // capability names, e.g. "acme/auth-provider"
requires?: Record<string, string>; // capability → provider version range (checked, not ordering)
schemaVersion?: number;
setup?: (config: NextlyServiceConfig) => NextlyServiceConfig; // all setups before any init; receives copies, no live handles
init?: (ctx: PluginContext) => void | Promise<void>;
onReady?: (ctx: PluginContext) => void | Promise<void>; // after every init and route registration; @experimental
onInstall?: (ctx: PluginContext) => void | Promise<void>; // `nextly plugins install`, after its migrations; @experimental
onUninstall?: (
ctx: PluginContext,
opts: { keepData: boolean }
) => void | Promise<void>; // `nextly plugins uninstall`, before its DOWN migrations; @experimental
onMigrate?: (
ctx: PluginContext,
run: { applied: number }
) => void | Promise<void>; // after a `nextly migrate` that left nothing pending; @experimental
destroy?: (ctx: PluginContext) => void | Promise<void>;
rename?: (map: Record<string, string>) => PluginDefinition; // integrator-side remap
}name is unique among the app's plugins, and app is reserved, in any letter case: the site's
own permissions are stored under the owner app and a plugin's under its name, so startup and
every CLI command refuse a plugin named app (PLUGIN_RESOLUTION_ERROR, logContext.reason
plugin-name-reserved). Choose another name.
PluginContributions
interface PluginContributions {
collections?: CollectionConfig[];
singles?: SingleConfig[];
fieldGroups?: FieldGroupConfig[];
extend?: Array<{ target: string | string[]; fields: FieldConfig[] }>;
permissions?: PluginPermission[]; // { action, resource, label?, description?, group? }
fieldTypes?: PluginFieldType[]; // custom field types — see below
events?: Array<{ name: string; durable?: boolean }>; // each must begin with your slug and a dot, or boot fails; `durable: true` lets you emitDurable it
routes?: PluginRoute[]; // { method, path, handler, requiredPermission?, public?, middleware?, rateLimit?, rawBody?, csrf?, noStore?, formatTimestamps?, mount? }
auth?: PluginAuthContributions; // hooks, challenges, ui — see Auth extensibility
settings?: ZodObject; // gives ctx.settings
settingsPermission?: PermissionSlug; // one of your own permissions; replaces update-settings for writes and the settings page
audit?: PluginAuditDeclaration; // gives ctx.audit
hookPoints?: PluginHookPointDeclaration[]; // your slug and a dot, never core's prefixes, or boot fails
dashboard?: DashboardContribution; // @experimental: { widgets?, suggest?, alternatives?, attention? } — see Dashboard widgets below
admin?: {
menu?: PluginMenuItem[]; // { label, to, icon?, order?, requiredPermission?, children? }
pages?: PluginAdminPage[]; // { path, component, requiredPermission?, startupReads? }
settings?: { component: ComponentPath };
views?: Record<string, PluginCollectionView>; // list/edit/before*/after*, and @experimental documentViews, documentActions, panelSections and foldedPanel, by collection slug
documentViews?: PluginFieldTypeDocumentView[]; // @experimental: views on every collection or Single with a field of one of this plugin's field types, at the top level, inside named groups, or in a repeater's rows
places?: PluginAdminPlaceDeclaration[]; // @experimental: { name, description? }, places on your own pages; your slug and a dot, or boot fails
filters?: PluginListFilterDeclaration[]; // @experimental: { name, label, collections?, options: [{ value, label, where }] }, in the entry list's toolbar
};
}Component references are string paths: "<package>/<path>#<Export>", e.g. "@acme/x/admin#ReportsPage".
Dashboard widgets
A plugin adds dashboard widgets one way: defineWidget declarations under
contributes.dashboard.widgets. Startup refuses the older admin.widgets and widgetSources
keys, naming this one.
import { definePlugin, defineWidget } from "@nextlyhq/plugin-sdk";
const ordersThisMonth = defineWidget({
id: "acme/orders-this-month",
title: "Orders this month",
description: "How many orders came in over the last 30 days.",
size: { default: { w: 3, h: 2 } },
view: "figure",
load: async ({ services }) => ({
total: await services.count("orders", { window: { range: "30d" } }),
}),
});
export default definePlugin({
name: "@acme/nextly-plugin-orders",
version: "1.0.0",
nextly: ">=0.0.2-alpha.63",
contributes: {
dashboard: { widgets: [ordersThisMonth] },
},
});suggest asks for a place on the default dashboard, alternatives offers a widget in place of a
built-in one, and attention adds lines to Needs your attention. Dashboard widgets
covers the views, what each load returns, and drawing your own component.
PluginContext (ctx)
interface PluginContext {
services: {
// managed, secure-by-default; each a frozen facade of its plugin methods
collections: PluginCollectionService; // access methods take { as: 'user' | 'system' }
users: PluginUserService; // @experimental type
media: PluginMediaService; // @experimental type
email: PluginEmailService; // @experimental type
versions: PluginVersionsService;
singles: PluginSinglesService; // @experimental
jobs: JobsNamespace; // @experimental
plugins: Record<string, Record<string, unknown>>; // @experimental
};
db: PluginDatabase & { raw: PluginRawDatabase }; // typed, owner-checked; .raw = Drizzle builder + transaction, the live instance only with capabilities.db.rawSql AND db.rawSqlPlugins
dialect: SupportedDialect; // "postgresql" | "mysql" | "sqlite"; read when accessed; @experimental
auth: PluginAuthApi; // always present; completeLogin needs the boot's login grant: capabilities.auth.login or a determineUser hook, AND the auth.loginPlugins listing
settings?: PluginSettingsApi; // with contributes.settings
fetch?: typeof fetch; // with a non-empty capabilities.net.outbound
audit?: PluginAuditApi; // with contributes.audit
hooks: PluginHookRegistry; // in-transaction, modify/abort
events: PluginEvents; // post-commit, observe-only, best-effort
filters: PluginFilterRegistry; // transform values on typed seams
actions: PluginActionRegistry; // ordered side-effects on typed seams
self: {
name: string;
collections: Record<string, string>;
singles: Record<string, string>;
}; // resolved slugs
config: PluginConfig; // @experimental; a copy of the plain configuration values, frozen all the way down — see below
logger: Logger;
nextlyVersion: string;
}PluginConfig
type PluginConfig = FrozenCopy<
Pick<
NextlyServiceConfig,
| "basePath"
| "preview"
| "schemasDir"
| "migrationsDir"
| "runMigrationsOnBoot"
| "strictPluginTargets"
| "permissions"
| "roles"
| "jobs"
| "collections"
| "singles"
| "fieldGroups"
| "users"
| "apiKeys"
| "security"
| "admin"
| "auth"
| "localization"
| "webhookRetention"
| "auditRetention"
| "emailRetention"
| "webhookAuditEnabled"
> & {
plugins?: readonly PluginSummary[];
email?: PluginEmailSettings; // the email settings without providerConfig
}
>;
interface PluginSummary {
readonly name: string;
readonly version: string;
readonly enabled: boolean; // false when configured with enabled: false
readonly capabilities?: FrozenCopy<PluginCapabilities>; // a copy
readonly contributes?: {
readonly declarations?: Readonly<Record<string, unknown>>;
}; // a copy
}Every plain object and array is copied and frozen; functions and class
instances are kept by reference. adapter, db, pluginConsent,
storagePlugins, imageProcessor, logger, hookRegistry, passwordHasher
and rateLimit are not on it. All three types are @experimental.
FrozenCopy<T> makes every property readonly and every array a readonly
array, all the way down, matching the frozen value: a write that would throw at
runtime does not compile. Each property's type is FrozenValue<T[K]>, which
keeps a function (a hook, a validator, a component) and a built-in instance
such as a Date or a Map as they are. Both types are exported
(@experimental) from nextly and @nextlyhq/plugin-sdk, so a plugin's
declaration files can name them. A helper that takes part of ctx.config
types its parameter from it, PluginConfig["collections"] or
FrozenCopy<CollectionConfig>, rather than as the mutable CollectionConfig:
spreading the array ([...collections]) is not enough, since each entry in it
is still frozen and still typed readonly.
Transactions
ctx.db.transaction(work: (tx: PluginTransaction) => Promise<T>, options?: { isolation?: "snapshot" }): Promise<T>;
// PluginTransaction = PluginDatabase without `transaction`; calling one rejects (INVALID_INPUT, nested-plugin-transaction)
// insert / insertReturning take PluginInsert<T>: InferInsert<T> with the col.id() key optional; ctx.db fills a UUIDv7
// options.isolation "snapshot": read-only, every read sees one moment (REPEATABLE READ on PostgreSQL and MySQL;
// SQLite's transactions are serial already); a write through tx rejects (INVALID_INPUT, write-in-snapshot-transaction)
ctx.db.raw.transaction(work: (tx: DatabaseInstance) => Promise<T>): Promise<T>;
// PluginRawDatabase: the fluent builder; the live Drizzle instance with rawSql granted
ctx.services.collections.withTransaction(work: (tx: PluginCollectionTransaction) => Promise<T>): Promise<T>;
// tx is an opaque token for createEntryInTransaction / updateEntryInTransaction / deleteEntryInTransactionSecure-by-default services
// Acts as the current user (RBAC enforced):
await ctx.services.collections.listEntries(
slug,
{},
{ as: "user", user: ctx.user }
);
// Privileged work — explicit, visible elevation:
const { item, warnings } = await ctx.services.collections.createEntry(
slug,
data,
{ as: "system" }
);Writes (createEntry, updateEntry, deleteEntry) resolve to the same
{ message, item, warnings? } envelope the Direct API and the REST API return.
warnings is present only when a post-commit hook failed: the row is already
saved at that point, so the write succeeds and the failure travels beside it.
Reads are unchanged and return their value directly.
Hooks & events
ctx.hooks.on(type, collectionSlug | "*", handler); // beforeCreate/afterCreate/… — can modify/abort
ctx.hooks.onInTransaction(collectionSlug | `single:${slug}` | "*", handler); // @experimental: inside the write's transaction, with a bound `db`; throwing aborts; may run again on a retry
ctx.hooks.onCollectionDelete({ impact?, inTransaction? }); // @experimental: what deleting a collection takes with it, for the delete dialog, and its removal in the delete's transaction; throwing refuses the delete
ctx.events.on(eventName, handler); // observe-only; e.g. `collection.${slug}.created`
ctx.events.emit(eventName, payload, { tx }?); // your own `<slug>.…` names, declared in contributes.events; delivered once the work commitsctx.events.emit delivers an event once the work that emitted it commits, and
never for work that was undone:
- With
{ tx }, the handlectx.db.transactionpasses its callback, the event is delivered once that transaction commits, and dropped if it rolls back, from whichever code emits it. A handle whose transaction has already ended is refused: emit withouttxonce the transaction has returned. - Called inside a transaction your code is running in without passing
tx, such as from anonInTransactionhook or a service call insidectx.db.transaction, it waits for the outermost transaction to commit. A savepoint that rolls back drops the events emitted inside it, and an attempt that is retried drops its own, so each is delivered once. - Outside any transaction, as from a job, a route or
init, it is delivered at once, as before.
await ctx.db.transaction(async tx => {
await tx.insert(orders).values(order);
ctx.events.emit("acme-billing.charged", { orderId: order.id }, { tx });
}); // listeners hear `acme-billing.charged` here, after the commitBefore this release emit delivered at once wherever it was called, even inside a
transaction that later rolled back. A listener now hears an event emitted inside a
transaction only after that transaction commits.
Durable events (@experimental)
An emit reaches the listeners running in this process when it is delivered, and
no further: a handler that throws, or a server that stops, loses it. A durable
event is written to the database with the work that emits it, and handed to every
subscriber until each has it.
// Declared in contributes.events with `durable: true`.
await ctx.db.transaction(async tx => {
await tx.insert(orders).values(order);
await ctx.events.emitDurable(
"acme-billing.charged",
{ orderId: order.id },
{ tx }
);
});
// Any plugin, in its init: a subscriber named within the plugin.
ctx.events.onDurable("acme-billing.charged", "award-points", async event => {
// May run again for one event: de-duplicate on event.id.
await awardPointsOnce(event.id, event.payload.orderId);
});emitDurable(name, payload, { tx }?)records the event by the same rule asemit: in the transactiontxnames, else in the one your code is running in, else in one of its own. It commits and rolls back with that work, a savepoint included, and resolves with the event'sid. Only names your plugin declaresdurable: trueare accepted; the payload is a JSON object of at most 64 KB.onDurable(name, subscriber, handler)subscribes under a name unique within your plugin: 1 to 64 lower-case letters, digits, dots, dashes or underscores, starting with a letter or digit. A delivery is owed to that name, so it reaches the same handler after a restart, however subscribers were added or reordered. Each subscriber registered when an event is dispatched gets one delivery. A plugin reloading in development is still owed what is dispatched before it registers again. In a rolling deployment, an instance still running the previous release dispatches with that release's subscribers, so a subscriber you add receives the events dispatched once every instance runs it.- Deliveries run on the
events:dispatchjob, and promptly once the emitting work commits inside a request. A handler that throws is tried again with backoff, across restarts, up to 10 times; a delivery whose subscriber is no longer registered is held for it.nextly events reportlists the deliveries that need an operator, andnextly events abandongives them up. - Finished events are removed 30 days after their last delivery settles.
A hook that learns something true about the state a write leaves behind, rather
than something that failed, tells the person whose write it is with
recordAdvisoryNotice({ phase, collection, code, message, entryId? }) from
@nextlyhq/plugin-sdk (@experimental). The write still reports success, and
the admin shows the notice beside it in an info toast, as it shows core's own
advisories. Put nothing in message the person could not already see; outside a
request it does nothing.
Event-name constants are exported: DocumentEvents, AuthEvents, MediaEvents,
and UserEvents (@experimental). Core emits user.created and user.deleted
with { userId } once the change has committed, so a hook or a plugin write that
rolls back sends nothing. A plugin subscribes to them and cannot emit either.
A plugin emits and declares only names beginning with its own slug and a dot, the slug
being pluginAdminSlug(name): @acme/billing emits acme-billing.charged.
ctx.events.emit throws FORBIDDEN for any other name, core's included, and a name in
contributes.events outside the slug fails boot (plugin-event-outside-namespace).
Typed slugs (codegen)
CollectionSlug, SingleSlug, PermissionSlug, and EventName are string by default and narrow to the installed unions once nextly generate:types runs. Author code stays valid either way.
Client (/client)
useCan(permission: string): boolean;
const Can: React.FC<{ permission: string; fallback?: ReactNode; children: ReactNode }>;Admin registration (/admin)
registerComponent(path, Component);
registerComponents({ [path]: Component });registerKnownPlugin(packagePrefix, register) is deprecated, and removed at the next major release after two minor releases. It still runs register straight away and says once that it is deprecated. Call registerComponents in your admin module instead: the generated component map imports that module, so every component it registers is there before a page asks for it.
When you run nextly generate:types, a plugin-admin-imports.generated.ts is emitted that registers your components for you, with a plugin-admin-components.generated.ts listing its paths. It calls registerComponentMap (experimental), which registers them as registerComponents does and then tells the admin the map is complete, so a component missing from it draws its fallback rather than loading. The app's admin page imports the first, and its server layout hands the second to checkAdminComponents from nextly/runtime, which writes the pair again in development when it falls behind, so your contributes.admin and contributes.dashboard components load with no manual wiring. nextly generate:types --check holds the committed pair to the config in CI. See Admin UI for how the map stays current.
Testing (/testing)
createTestNextly(opts: {
plugins: PluginDefinition[];
collections?: CollectionConfig[];
dialect?: "sqlite" | "postgresql" | "mysql"; // default sqlite (in-memory)
serverUrl?: string; // else TEST_POSTGRES_URL / TEST_MYSQL_URL
pluginConsent?: { rawSql: readonly string[] }; // @experimental; the test's db.rawSqlPlugins
basePath?: string; // where generated files go; else a temporary folder
}): Promise<{ nextly; getService; hooks; events; adapter; basePath; destroy }>;
getConfiguredTestDialects(): TestDialect[]; // sqlite, plus any whose server URL is setCustom field types (contributes.fieldTypes)
A plugin can add a field type. It persists as one of the existing storage primitives — the plugin never invents DDL — and renders through its own admin component.
interface PluginFieldType {
type: string; // field.type value, e.g. "rating". Must not collide with a built-in
storage: FieldStoragePrimitive; // text | longText | boolean | number | timestamp | json
component: ComponentPath; // "<package>/<path>#<Export>"
label?: string; // picker label; defaults to a title-cased `type`
description?: string;
icon?: string; // Lucide icon name
category?: FieldTypeCategory; // picker grouping; defaults to "Advanced"
surfaces?: FieldSurface[]; // where it may be offered; defaults to entries/singles only
layout?: "takeover";
validate?: (value, args) => true | string | PluginFieldIssue[] | Promise<…>; // see below
validateEmpty?: boolean; // experimental: hand `validate` an emptied value too
validateOptions?: (field) => true | string | PluginFieldIssue[]; // see below
}validate — the type's own rules
Without it a custom type is only ever checked as its storage primitive: a
json-backed type would accept any JSON at all. Declare the rules on the type
and every instance gets them, rather than each schema author remembering to
repeat a field-level validate.
fieldTypes: [
{
type: "rating",
storage: "number",
component: "@acme/ratings/admin#RatingInput",
validate(value, { field }) {
// Already a number: the `number` primitive's rules ran first.
if (typeof value !== "number" || !Number.isInteger(value)) {
return "Rating must be a whole number";
}
const max = typeof field.max === "number" ? field.max : 5;
if (value > max) return `Rating cannot exceed ${max}`;
return true;
},
},
];args carries:
| Key | What it is |
|---|---|
data | The write payload, for rules spanning fields. On update this is the patch, not the merged stored entry. Always the top-level payload, even for a field nested in a repeater row. |
req | Request context; carries user when authenticated. Empty for a field inside a field group instance. |
field | The instance, so you can read the options your type declares. A detached copy: records, arrays, dates, sets and maps are rebuilt, so editing them changes nothing. Functions and class instances stay shared — treat it as read-only. |
path | Where this field sits in the write ("stars", "rows[1].stars"). |
mode | "create" or "update". |
write | Experimental. The entry write this value belongs to: kind ("collection" or "single"), slug, id, inTransaction, and readStored (below). id is the id the entry is stored under: the stored id on an update, and on a create the caller's own id where the collection accepts one (db.allowIdOnCreate); it is absent on any other create, and for a single. inTransaction says whether the write runs inside a transaction (a batch, an import). write itself is absent when no entry write is behind the validation — a default value being judged, or a call to validateFieldValues. Use mode, not the presence of id, to tell a create from an update. |
Return true to accept, a string for one problem, or an array when one value
can be wrong in several places at once. Issue paths are used as given, so build
them from args.path or they will be wrong for a nested instance:
return [
{
path: `${path}.nodes[2]`,
code: "DISALLOWED",
message: "That block is not allowed here",
},
{ message: "Document exceeds the node limit" }, // path/code default to the field's own
];Ordering: the built-in rules for your storage primitive run first, then this,
then the field's own validate — so a schema author adds rules on top of yours
rather than replacing them. Two values never reach validate: an absent one
(that is what required is for) and one the storage primitive already refused,
so you never have to re-check that you were handed the shape your type stores.
For json that check is representability — a cycle or a BigInt is rejected
before you see it — and nothing more, so the shape of the document is yours to
define.
Experimental: a type that sets validateEmpty: true is also handed a value a write
empties (null or ""), for content a write must not drop unasked, such as the
blocks an author locked. Its required issue is still reported as before.
Judging a value against stored rows: write.readStored
Some rules are about the rows around a value rather than the value alone — a
document that places another document that places it back. write.readStored
reads one stored value of your own field type, on the connection the write
runs on:
async validate(value, { write }) {
// No write behind it, or an entry nothing can name yet. Whether this is a
// create is `mode`'s to say: `id` is set on a create too where the collection
// accepts the caller's id (`db.allowIdOnCreate`).
if (write?.id === undefined) return true;
const other = await write.readStored({
collection: "components",
id: "b",
field: "content",
form: "draft", // or "published"
});
if (other.kind === "absent") return true;
// other.value is the stored document
return true;
}- The write's own connection. Inside a batch or an import, that is the
batch's transaction, so rows the same batch wrote before this one are seen.
Before a single write's transaction opens, it is the pool. When
write.inTransactionis true, a read of your own on another connection (the Direct API) cannot see those rows, and can wait on the connection the transaction holds. - As the system. No read hooks and no access rules shape the answer: a value a hook hides from a reader is still what that reader's page is built from.
- Your type only. A field of your own type, in any collection: a top-level
one, or one inside named groups, named by its path (
field: "hero.body"). Another field, a field of another type, a field in a repeater's rows or a field-group instance, or a localized field is refused with an error naming it. form."published"is the live row."draft"is what an editor's preview reads: the pending working draft where one is shown, otherwise the live row.
readStored reads, and nothing it returns is written. Validation runs before
beforeChange hooks, so what it judges is the value as submitted; a hook that
replaces the value afterwards is not judged again.
Anything you return outside true | string | PluginFieldIssue[] is a refusal,
as is throwing — a validator that forgets to return fails the write rather than
silently accepting everything.
Where it runs. The entry, single, and field group write paths. A type offered
on the users, forms, or blocks surface does not run it yet: those
surfaces validate through their own paths. A disabled plugin keeps its field
types registered (its collections are retained) but its validate does not
run — that is behavior, and a disabled plugin contributes none.
validateOptions — rules about the declaration
validate answers "is this value allowed in this field". validateOptions
answers "is this field declared coherently at all". It runs when a schema is
registered, not when a value is written.
The distinction matters because a schema defect reported per write is reported to the wrong person: the writer cannot fix it, and it fails every write until whoever declared the field notices.
validateOptions(field) {
const policy = field.policy;
if (policy === undefined) return true;
if (policy === null || typeof policy !== "object") {
return [{ path: "policy", message: "policy must be an object" }];
}
const { kinds } = policy as { kinds?: unknown };
if (Array.isArray(kinds) && kinds.length === 0) {
// Nothing could ever be stored in this field. That is a contradiction in
// the declaration, not a problem with any particular value.
return [{ path: "policy.kinds", message: "policy.kinds cannot be empty" }];
}
return true;
}Synchronous on purpose: a declaration is checked against itself, and a
config-time rule that needed I/O would make startup depend on something that can
be down. Issue paths are relative and get appended to the field's own, so
"policy.kinds" reports against fields[2].policy.kinds — unlike validate,
whose paths are absolute, because this one only ever names an option it already
knows and has no way to learn its own index. Throwing is a rejected declaration,
not a crash. A returned code is not carried: config errors report through
closed, public code unions, so the canonical member is used and your message
carries the detail.
Where it runs. Every path a declaration reaches storage by:
| Path | When |
|---|---|
| boot | over the resolved config and a plugin's own raw contributions, once the registry is populated |
db:sync and its watcher | before anything is serialized or materialized |
| Schema Builder writes | before the payload is stored, and again before the manifest is written |
| direct collection/single/field-group create and update | before the definition is persisted and its DDL runs |
nextly build | over collections, singles and field groups |
migrate:create | over the merged set the migration is generated from |
| HMR reload | after the reload repopulates the registry |
Not the define* calls, despite their being where a code-first config is
validated. The config bundle is evaluated before contributes.fieldTypes is
registered, so a custom type is not yet known at that point and the define call
rejects it as an unknown field type before any option check could run. Do not
reach for defineCollection to get your declaration checked — that ordering is
why every gate above sits after registration.
Your check always sees the declaration as written. On the Builder path that is the submitted payload, not the parsed copy: the manifest schema drops keys it does not declare, while the write persists the original, so your options are present in what gets stored and absent from what was parsed.
A disabled plugin runs neither hook. Its field types stay registered, because its
collections are retained and their fields still have to map to a column and
render, but validate and validateOptions are both dropped at registration —
they are behavior, and a disabled plugin contributes none.
Where your options live. An option written directly on the field is read as
written, and that is the ergonomic choice while its name differs from every key
the field schema declares — options, fields, admin, label and the rest of
the built-in field surface. The manifest applies the built-in shape to every
field whatever its type, so a name that does collide is judged against the core
meaning (options as a select's choice array) and rejected before your check
runs.
For a name core already uses, or to be safe against names core may add later,
put the option in the pluginOptions container. Core never looks inside it, so
any name is legal there:
{
"name": "rating",
"type": "star-rating",
"pluginOptions": { "options": { "presets": ["a", "b"] } }
}Both are read, and your type is handed one flat view either way, so
field.options above resolves to your object without your having to know where
it was stored. The container wins when the same name appears in both. Writes
from the Schema Builder go to the container, so a field stored the older way
moves there the next time it is saved; nothing you read changes when it does.
Two names are reserved inside the container: type and name. The instance
you are handed states which field it is under those keys, restated after your
options are folded in, so an option using either would be shadowed and never
reach you. A manifest write declaring one is refused rather than silently
losing it.
Fields nested in a repeater or group are covered. A type offered only on the
users, forms, or blocks surface is not: those surfaces have their own
config validators, which do not consult this registry.
Declaring one on the users surface from code. UserFieldConfig is a union
of the built-in field shapes, so a select missing its options fails on its
own shape. A plugin type's token is not knowable there, and an arm open enough
to accept it would accept that malformed select too and lose the error. Wrap
the declaration in pluginUserField() instead, which marks it as belonging to
the open arm:
import { defineConfig, pluginUserField } from "nextly";
export default defineConfig({
users: {
fields: [
{ name: "company", type: "text" },
pluginUserField({ name: "score", type: "star-rating" }),
],
},
});Options are optional there: pass pluginOptions, write them directly on the
field, or pass none at all. Note that these options reach type generation but
are not persisted, so a field read back from the database after boot carries
none of them.
Providing page metadata
One plugin can work out the head of every page the site serves: its title, description,
canonical address, whether search engines may list it, its social card and its language links.
It declares the page-metadata capability and contributes its resolver as the pageMetadata
service:
import { definePlugin, type PageMetadataResolver } from "@nextlyhq/plugin-sdk";
const resolver: PageMetadataResolver = {
resolve: input => ({
title: input.code.title ?? input.derived.title,
description: input.code.description ?? input.derived.description,
robots: { index: true, follow: true },
}),
// What the answer depends on beyond the page's own document.
tags: () => ["acme-seo:settings"],
};
export default definePlugin({
name: "@acme/nextly-plugin-seo",
version: "1.0.0",
nextly: ">=0.0.2-alpha.74",
provides: ["page-metadata"],
contributes: { services: { pageMetadata: () => resolver } },
});The route helpers in nextly/runtime and @nextlyhq/blocks-react/next then ask it for every
page they serve, with no change to the site's routes. resolve is told:
| Field | What it holds |
|---|---|
path | The address the page was served at, from /. Absent for a Single route, which is never told where the app mounts it. |
locale | The language the route read the page in, when the route states one. |
source | The document: { kind: "entry", collection, entry } or { kind: "single", slug, document }, as read for this request. |
code | The title, description and social values the route's own buildMetadata or metadata set. A route never supplies visibility or the canonical. |
derived | What the page's content offers, such as the title, description and picture a Page Builder page's blocks show. |
It answers a PageMetadataAnswer: title, description, canonical, robots, social,
languages and structuredData, each optional. The route turns the answer into Next.js
Metadata. Whatever else the route's own metadata set, such as an Open Graph type, is kept.
structuredData is the page's JSON-LD: a list of nodes, written without @context, holding plain
JSON only. The route hands it to the page's render as context.structuredData, one schema.org
graph written so that no value can end its script element. An answer whose structured data is not
JSON is refused whole, as any answer of the wrong shape is.
The answer is cached with the page: it expires when the page's document changes, and when any tag
tags names is expired, so a change to the plugin's settings reaches every page without a
redeploy. If resolve throws, the error is logged and the page is served with the route's own
metadata.
Only one plugin may provide page-metadata, and boot refuses a plugin that declares it without a
pageMetadata service. The types are @experimental.
Secrets
secret(value): Secret<T>; // auto-redacts in logs / JSON / inspect; .reveal() to read
isSecret(v): boolean;See the author guide for the full workflow and the error reference for boot-error meanings.
Runtime surfaces added for stateful plugins
ctx.settings is present only when the plugin declares
contributes.settings, ctx.fetch only with a non-empty
capabilities.net.outbound, and ctx.audit only with contributes.audit, so
a plugin that never asked for one does not have it. They are typed as optional
on PluginContext; read them through a guard that names the missing
declaration. ctx.auth and ctx.filters are always present.
ctx.settings
Declare contributes.settings (a zod object) to get it.
if (!ctx.settings) throw new Error("declare contributes.settings");
const config = (await ctx.settings.get()) as MySettings;
await ctx.settings.set({ apiKey: "..." }, { actorUserId: user.id });Values are parsed by the declared schema, and the paths named in
capabilities.secrets are encrypted at rest. See
security for what is and is not returned to the admin.
set is a JSON merge patch (RFC 7396):
keys you leave out keep their stored value at every depth, and a key set to
null is removed, so set({ providers: { github: null } }) deletes one entry
of a record. The result is validated as a whole, and a key the schema does not
declare is refused at any depth. One key's stored value may be at most 256 KiB.
get throws an internal error when the stored settings no longer fit the
schema — for example after an update added a required key — or hold a secret
nothing can decrypt; the log names the plugin and the paths, and the admin
settings page still opens and shows what is missing.
After any change, from the admin or from ctx.settings.set, core emits
plugin.settings.changed with { plugin, changedKeys } (key names, never
values), and an operator's change is recorded in the activity log by key name.
ctx.fetch
Declare a non-empty capabilities.net.outbound to get it.
if (!ctx.fetch) throw new Error("declare capabilities.net.outbound");
const res = await ctx.fetch(
"https://accounts.google.com/.well-known/openid-configuration"
);Reaches only the declared hosts, and only addresses outside your own network.
ctx.audit
Declare contributes.audit to get it.
if (!ctx.audit) throw new Error("declare contributes.audit");
await ctx.audit.write({
kind: "acme-auth.identity-linked",
actorUserId: user.id,
metadata: { provider: "google" },
});A kind is the plugin's own admin slug, a ., a lowercase letter or digit, then
any of lowercase letters, digits, ., _ and -; a kind outside that, longer
than the audit column, or declared twice fails boot. Undeclared kinds and keys
are dropped rather than stored. targetUserId must name an existing user; a
row naming one that does not exist is stored without its metadata, and a
warning is logged. A person your plugin signs in
goes in actorPrincipal or targetPrincipal, never in the user ids.
ctx.auth
Always present. completeLogin requires the boot's login grant — the plugin
declares capabilities.auth.login or contributes a determineUser hook, and
the app lists it in auth.loginPlugins (an unlisted login-capable plugin
refuses the boot naming the line to add) — and a strategy name beginning with
the plugin's own slug.
return ctx.auth.completeLogin(user.id, {
request,
strategy: "acme-google-auth:google",
next: "/admin",
});Also ctx.auth.currentUser(request) and ctx.auth.verifyCsrf(request). currentUser answers null to a POST, PUT, PATCH or DELETE whose Origin (or, without one, Referer) is neither your site nor an allowed origin, or that names no origin, as it does to a request with no session; when that request carried the session cookie, the route records a csrf-failed audit event. verifyCsrf accepts the token in the x-csrf-token header or as csrfToken in a JSON body; it reads at most 64 KB of a body looking for it, and refuses a larger one with reason: "body-too-large", so a large request sends the token in the header.
A plugin that computes the next destination from something a caller sent reduces it with sanitizeAdminPath (@experimental, exported from the SDK): anything that is not a same-origin path under /admin answers DEFAULT_ADMIN_PATH (/admin) rather than raising, so a login route cannot be turned into an open redirect.
ctx.filters.decide
For a seam where handlers VETO rather than transform.
const verdict = await ctx.filters.decide(
"acme-auth.may-link",
{ allow: true },
{ userId }
);A handler that throws denies, and a handler may only keep or downgrade the verdict — so the order plugins load in cannot decide access.
Typed hook points
ctx.filters and ctx.actions take their types from HookPointPayloads
(@experimental), keyed by the point's name. Core's seams (email.beforeSend,
email.afterSend, admin.nav, collections.listQuery) are listed; a plugin
lists the points it publishes by augmenting the interface:
declare module "@nextlyhq/plugin-sdk" {
interface HookPointPayloads {
"acme-auth.profile": {
kind: "filter";
value: { displayName: string };
context: { userId: string };
};
"acme-auth.may-link": { kind: "decision"; context: { email: string } };
"acme-auth.linked": { kind: "action"; payload: { userId: string } };
}
}A listed point's handlers and calls are then checked against its entry, and one
used through the wrong registry (a decision through apply, say) does not
compile. A name with no entry is typed by the call site, as before.
A point in contributes.hookPoints begins with the plugin's own slug and a dot,
and never with a prefix core's seams use (email., admin. and
collections.), whatever the plugin's slug. Boot fails on a point under core's
prefixes (hook-point-reserved), outside the plugin's slug
(hook-point-outside-prefix), or declared by two plugins
(hook-point-collision, naming both).
Admin places
Admin pages have named places a plugin can add to (@experimental). Core names
one per page, and the entry form within the edit pages: dashboard, collection.list, collection.edit, single.edit,
entry.form, settings, user.detail, account and login, exported as
CORE_ADMIN_PLACES. A place id is typed AdminPlaceId, a closed set, so a
misspelled place does not compile.
A plugin declares places on its own pages in contributes.admin.places, each
named with its slug and a dot, and types them by augmenting AdminPlaces:
definePlugin({
name: "@acme/billing",
// …
contributes: {
admin: { places: [{ name: "acme-billing.invoice" }] },
},
});
declare module "@nextlyhq/plugin-sdk" {
interface AdminPlaces {
"acme-billing.invoice": { context: { invoiceId: string } };
}
}Boot fails, naming the plugin and the place, on a place that is malformed
(admin-place-malformed), declared by a plugin whose slug is a segment core
reserves (admin-place-reserved-slug), under one of core's segments
(admin-place-reserved), outside the plugin's slug
(admin-place-outside-namespace), or declared twice (admin-place-collision).
A contribution to another plugin's place names that plugin in dependsOn, or in
optionalDependsOn where the contributor works without it: while the owner is absent or
disabled, a contribution to one of its places is left out and the app starts. A place the
running owner does not declare is still refused (admin-place-unknown), as is one of a plugin
the contributor names in neither.
Every core place draws what is sent to it: settings, a user's detail page, the
account page, the entry form, the login page, both edit pages, the dashboard
and the entry list. A plugin draws its own
place on one of its pages with TargetSlot and PlaceTabs from
@nextlyhq/plugin-sdk/admin (@experimental), the parts core's pages use:
import { PlaceTabs, TargetSlot } from "@nextlyhq/plugin-sdk/admin";
// The plugin's own invoice view.
import { Invoice } from "./Invoice";
// The place's type, as declared above, so its id and context are checked.
declare module "@nextlyhq/plugin-sdk" {
interface AdminPlaces {
"acme-billing.invoice": { context: { invoiceId: string } };
}
}
export function InvoicePage({ invoiceId }: { invoiceId: string }) {
const context = { invoiceId };
return (
<PlaceTabs
place="acme-billing.invoice"
context={context}
contentLabel="Invoice"
>
<Invoice id={invoiceId} />
<TargetSlot place="acme-billing.invoice" context={context} />
</PlaceTabs>
);
}Each block and tab is drawn in the order sent, behind its own error boundary,
and receives the place's context (and entry, where the page passes one).
Pass context={null} while the page does not know its ids yet: nothing
contributed is drawn until it does, so no contribution is handed a wrong id.
With no tab sent, PlaceTabs draws its children alone; with one, they are the
first tab, under contentLabel. className styles the strip and the
contributed tabs' panels, never the children, so a page that insets its
content can line them up with it. A plugin's place has no built-in parts, so
the page draws its own content beside the slot. TargetSlot takes a fallback,
drawn in the place's stead while nothing contributed is drawn there (once the
page knows its ids), and blockProps, handed to every block beside context
(both @experimental).
To draw something only where the admin's own page would draw a contribution,
ask useContributionApplies(place, id, document) (@experimental): true
exactly where the place's page draws it, for this reader, now. The document
is { kind: "collection" | "single", slug }; a tab that edits fields of the
document is judged against the fields of the document form around the caller,
or the fieldNames passed. The SEO plugin's tab in the Page Builder asks it
about the edit page's SEO tab, so the two are never out of step.
Entry-list filters
A plugin can add filters to the entry list's toolbar (@experimental). Each
option narrows the list by a where:
contributes: {
admin: {
filters: [
{
name: "acme-support.state",
label: "Ticket state",
collections: ["tickets"], // every collection's list when absent
options: [
{ value: "open", label: "Open", where: { state: { equals: "open" } } },
{ value: "closed", label: "Closed", where: { state: { equals: "closed" } } },
],
},
],
},
},Choosing an option adds its where to the list's own request, which the
server answers with the reader's access, so a filter only ever narrows what
they can already list. The choice is kept in the page's URL as
?pf=acme-support.state:open; one naming an undeclared filter or option is
ignored. A collection is named by the slug it was declared with: one a plugin
contributes follows that plugin's renames, so a filter still reaches it after
the host renames it.
Boot fails, naming the plugin and the filter, on a name outside the plugin's
slug (list-filter-outside-namespace), one declared twice
(list-filter-duplicate), or one with a key it does not take (a misspelled
collection, say), no label, no options, a collection slug no collection can
have, an option value a URL can't carry, two options with one value, or a
where the list could not read, malformed or nested too deep once joined to
the list's own filters (list-filter-invalid).
A reader is offered, on each collection, only the options whose where the
list read would let them filter by: an option naming a field they may not
read is not sent to them.
Admin contributions
A plugin can add blocks, tabs, list columns, row and bulk actions and side
panel sections to the admin's places (@experimental). Each is declared as
data under contributes.admin.contributions, names its place and its kind,
and the place must take that kind:
| Place | Takes |
|---|---|
dashboard, entry.form, login | block |
collection.list | block, column, rowAction, bulkAction |
collection.edit, single.edit | block, tab, sidebarSection |
settings, user.detail, account | block, tab |
A plugin's own place (contributes.admin.places) takes the kinds its
accepts names, blocks alone when it names none.
contributes: {
routes: [{ method: "POST", path: "/escalate", handler: escalate }],
admin: {
contributions: [
{
id: "acme-support.sla", // the plugin's slug and a dot
kind: "sidebarSection",
place: "collection.edit",
collections: ["tickets"], // every collection's page when absent
label: "SLA",
component: "@acme/support/admin#Sla",
after: "status", // after the built-in Status section, as close as it can
// @experimental: the reads the section makes as it opens, started with the page
// (collection.edit, single.edit and entry.form only; refused elsewhere)
startupReads: [{ path: "/sla?collection={collection}&entry={entryId}" }],
},
{
id: "acme-support.escalate",
kind: "rowAction",
place: "collection.list",
collections: ["tickets"],
label: "Escalate",
action: { run: { method: "POST", path: "/escalate" } }, // or { open: component }
requiredPermission: "update-tickets",
visibleWhen: { field: "status", notEquals: "closed" },
},
],
},
},Order. At each place, each kind's contributions are ordered by order
(lower first, 100 when absent), or relative to another contribution's id or a
built-in part's name: after: A places it after A, as close to A as the other
contributions' order allows, and straight after A when nothing competes, and
before is the same on the other side. A contribution that must come between
them keeps its place there. A contribution may take a
built-in part's place with replaces. The edit page's side panel names its
four built-in sections, in order: status, publishing, language and
details. Among blocks, the edit pages name the document bar, with the
banners under it, document-bar, and the editor, the fields with the side
panel, editor; settings and a user's detail page name the page's own
content content, the account page names its profile card profile, the
entry form names its fields fields, the entry list names its header
toolbar and its list table, and the login page names the sign-in form
form. A plugin that replaces the login page's form
takes over sign-in for the site.
The dashboard. Its blocks stand around the page's own two, the welcome
header welcome and the grid of cards widgets. A block placed by nothing
goes below the grid:
{
id: "acme-support.queue",
kind: "block",
place: "dashboard",
component: "@acme/support/admin#Queue",
}and one placed before the grid goes between the header and the cards:
{
id: "acme-support.alerts",
kind: "block",
place: "dashboard",
component: "@acme/support/admin#Alerts",
before: "widgets", // or after: "welcome"
}The grid is each person's own arrangement of their cards, so a block may stand
beside it but never replace it. welcome may be replaced.
On a phone. Where an edit page is too narrow to keep the side panel
beside the fields, the panel opens only when asked for. A side
panel section declared with narrow: "above-form" (@experimental) is drawn
there under the title, above the fields, and left out of the panel, so an
author meets it without opening the panel. Without it, the section stays in
the panel at every width.
Who sees one. Contributions are sent only in the signed-in workspace metadata, the login page's alone in the public one, and each reader receives only what they may see:
- A contribution with a
requiredPermissionthe reader lacks is not sent at all, so its label and action never reach them, and nor is an action whoserunroute asks a permission they lack. One that replaced a built-in part gives that part back. visibleWhenis a rule over the entry the page or row shows: a field compared withequals,notEquals,inorexists, combined withand,orandnot. It is allowed on a collection entry's edit page and on row and bulk actions; a Single's edit page and the entry form take none yet. A field the reader may not read is missing from what they read, and a rule needing it does not match,existsandnotincluded. A contribution whose rule names such a field is not sent to that reader at all.extendedWith(@experimental) names fields the plugin's ownextendadds. The contribution is then offered only on the collections, or on a Single's page the Singles, where the start added every one of them: a tab that edits a field a scope adds follows it to Schema Builder types, and skips a type that kept a field of its own by that name. Withcollectionsorsinglestoo, it is offered where both agree. Where the plugin's extension switch has one of those fields off on a type (EXTENSION_SWITCH_SERVICE, see Schema), it is not offered there, and the field is drawn nowhere in that type's editors.
The admin draws blocks and tabs at settings, a user's detail page, the account
page, the entry form, the login page, both edit pages and the dashboard, in the order sent,
each behind its own error boundary; a contributed tab follows the page's own content, which
stays as it was when no tab is sent. On an edit page the tabs head the field
column, and the document bar and the side panel stay whichever tab is open.
The side panel draws contributed sections among its own, each under its
label, and a section whose component draws nothing for a document leaves no
heading behind. A section's component receives SidebarSectionProps
(@experimental, from @nextlyhq/plugin-sdk/admin): the place's context
and entry, as every contributed component does, and on a collection entry's
page also the document's handles a panelSections section is given
(collectionSlug, entryId, documentLock, mayWrite,
documentChanged).
A contributed tab's component receives PlaceTabProps (@experimental): the
place's context and entry, and setBadge, which shows a count beside the
tab's label, or none with null. It stays mounted while another tab is open,
so what it holds is kept and its count stays current. A tab that applies to
some of the place's documents only calls setLeftOut(true) to leave the row,
and setLeftOut(false) to come back; it stays mounted, hidden, meanwhile. On an edit page it
receives DocumentTabProps (@experimental): those, the document form's
control, and the documentLock a side panel section is told, on a saved
entry, a new one and a Single alike. A tab reads what the author has typed and
not saved, and what it writes through control is stored by the bar's Save
and Publish with everything else. The open tab is kept in the address as
?tab=<id>, so a reload or a shared link opens it again.
A tab on an edit page may take over fields of the document with fields
(@experimental), a list of top-level field names. The page then draws those
fields in the tab instead of among its own content, and draws the tab only on a
document that has every one of them. Their values stay in the document's form,
so Save and Publish store them, and any surface that reads the document reads
them as before. While a past version of the document is on screen, the page
draws its own content alone and no contributed tab, since a tab reads the live
document. A contribution to a Single's edit page may name the Singles it
is for with singles, as one on a collection's page names its collections:
{
id: "acme-seo.tab",
kind: "tab",
place: "single.edit",
singles: ["homepage"], // every Single's page when absent
label: "SEO",
component: "@acme/seo/admin#SeoTab",
fields: ["seo"], // drawn in this tab, not among the page's fields
}import { useEffect } from "react";
import { useWatch } from "react-hook-form";
import type { DocumentTabProps } from "@nextlyhq/plugin-sdk/admin";
export function TitleCheckTab({ control, setBadge }: DocumentTabProps) {
// What the author has typed, saved or not.
const title = useWatch({ control, name: "title" });
const tooLong = typeof title === "string" && title.length > 60;
useEffect(() => {
setBadge(
tooLong ? { count: 1, label: "1 thing to fix", tone: "attention" } : null
);
}, [tooLong, setBadge]);
return (
<p>
{tooLong
? "The title is longer than a results page shows."
: "The title fits."}
</p>
);
}Any component a plugin draws inside an edit page, a block, a side panel
section or a tab, can read the document as it is being typed with
useDocumentValues and useDocumentField (@experimental, from
@nextlyhq/plugin-sdk/admin). A place's entry prop is the document as it
was read; these are the values before any save. useDocumentValues(paths)
answers the named fields by their dot paths and draws again only when one of
them changes. useDocumentField(path) answers one field's value, whether it
is writable now, and set(next), which writes as the author typing would
and marks the document changed. While the document's content is held (a past
version on screen, a colleague editing it, a page the reader may only read),
set writes nothing and answers false. set(null) returns a field to its
automatic value. Both read the editor's own form, so a component with a form
of its own still reads the document, and both answer null outside an editor.
import { useDocumentField } from "@nextlyhq/plugin-sdk/admin";
export function TitleLength() {
const title = useDocumentField("title");
if (title === null) return null;
const length = typeof title.value === "string" ? title.value.length : 0;
return <p>{length} characters</p>;
}The entry list draws blocks around its own header (toolbar) and its list
(table); declared columns after the collection's own, a field column through
that field's own cell and a component column one cell at a time, each cell
behind its own boundary and receiving the place's context and its row; row
actions in each row's menu, after its own, on the rows whose visibleWhen
holds; and bulk actions in the bar shown while rows are selected, offered when
the action's visibleWhen holds for every selected row.
Running an action. An action that opens a component draws it with the
rows it was run on. In a bundled admin, that component resolves only once
contribution components are collected into the generated import map; until
then the action shows the slot's fallback. One that runs a route calls the plugin's own route,
which must answer a write (POST, PUT, PATCH or DELETE) and must not be
public or a route for the plugin's own kind of signed-in person. The request
carries the action and its rows, with the CSRF token the admin sends with
every write:
{
"action": "acme-support.escalate",
"rows": [{ "collection": "tickets", "id": "42" }]
}A route bound to an action is reachable only as that action. Before its handler runs, every request to it must name one of the actions that run it and the rows it acts on: a row action exactly one, a bulk action up to 100. Declare a second route for any other use. The request is refused, and nothing of the plugin's runs:
400, when it names no action that runs this route, no rows, too many rows, or is not such a body;403, the route gate's own answer, when the caller lacks the action'srequiredPermission;404, when a row is missing or one the caller may not read; the two are not told apart;403ACTION_NOT_AVAILABLE, when a row is in a collection the action is not offered on, or itsvisibleWhendoes not hold for the row as the caller reads it. A field the caller may not read is missing from that row, so a rule needing it does not hold.
A bulk request is refused whole when any row fails. The rows are read once per collection, as the caller. Hiding an action in the admin is not its access control; this check is.
A staff route your person's-menu item runs (header.place: "menu" with an
action.run) is bound to that item too, under the id
<plugin-slug>.user-menu, and its request names no rows:
{ "action": "<plugin-slug>.user-menu", "rows": [] }. No rows are accepted for
that id alone, and only on the route the item names; a list action on the same
route still needs its rows.
Boot fails, naming the plugin and the contribution, on an id outside the
plugin's slug (admin-contribution-outside-namespace), one declared twice
(admin-contribution-duplicate), a place that does not exist
(admin-place-unknown) or does not take its kind
(admin-contribution-kind-not-accepted), a reference to nothing there
(contribution-order-unknown), contributions ordered before each other
(contribution-order-cycle, naming every one), a built-in part that is not
there (contribution-replace-unknown), replaced twice
(contribution-replace-twice), or kept whatever is contributed, as the
dashboard's widgets is (contribution-replace-not-allowed), and one that
is malformed
(admin-contribution-invalid): a key its kind does not take, no label or
component, fields that are not top-level field names or are named away from an
edit page, singles away from a Single's page, an action that names none of the plugin's own routes, or a route
that is public, a signed-in person's, or answers GET, a permission
on the login page, or a rule where there is no entry to judge.
Reading what other plugins declared
A plugin publishes static data for another to read with contributes.declarations,
keyed by the CONSUMING plugin's package name. Core stores what it is given and
reads inside none of it, with one exception: declarations addressed to
@nextlyhq/plugin-page-builder are parsed and validated by core itself, which
assembles them into the page builder's block manifest and component map. Read
what was addressed to you with collectDeclarations from
@nextlyhq/plugin-sdk, passing ctx.config.plugins, which lists every
configured plugin (name, version, enabled, capabilities, declarations):
import { collectDeclarations, type PluginContext } from "@nextlyhq/plugin-sdk";
// The plugin context, in init or a route handler.
declare const ctx: PluginContext;
const declared = collectDeclarations(
ctx.config.plugins ?? [],
"@acme/nextly-plugin-blocks"
);
// → [{ source: "@acme/pricing", value: { blocks: [...] } }, …]collectDeclarations only pairs and appends. Each entry names the plugin that
wrote the declaration, in plugin order, and it reports nothing itself, so
detecting and reporting two plugins whose declarations do not agree is the
CONSUMER's job — the page builder's block manifest names both and refuses. A
plugin configured enabled: false contributes nothing, and one that declared
nothing for you contributes no entry, so an empty answer means nobody declared.
It reads the plugin list alone, so it answers the same at boot and at
generation time.
Like leaving sql out of the query operators and the rawSql grant, this is a
reviewed channel, not an enforced boundary: plugins run as trusted code, and
nothing stops one reading ctx.config.plugins itself. collectDeclarations is
the one helper that pairs each declaration with its author, so a reviewer sees
who declared what rather than holding a value whose author it cannot name.
Lifecycle
onReady runs after every plugin has initialised and routes are registered.
onInstall and onUninstall (@experimental) never run at boot: nextly plugins install calls onInstall after the plugin's migrations, and nextly plugins uninstall calls onUninstall before its DOWN migrations, with
{ keepData }. Write both so they can run again: an install can be retried
after a failure part-way through. Work that must happen on every start, rather
than once per install, belongs in init.
onMigrate (@experimental) runs after a nextly migrate (or
nextly migrate:fresh) that left nothing pending, for an enabled plugin
installed on the database, with { applied }, the number of migrations the
run applied (0 when there was nothing to apply). It runs after migrate's lock
is released, so write it to be safe when two runs call it at once.
Before either command shuts the runtime down, it waits for the event handlers the hook set off, including those of the follow-up events they emit, for at most 30 seconds. A handler is waited for while the promise it returns is pending, so return the promise of work that must finish: work left to a timer, or to a promise the handler does not return, is not waited for. When that work is still running at the limit, the command stops; an uninstall stops before its DOWN migrations, and running it again finishes it.