Overview

Register optional features in cms.config, and write your own with definePlugin.

Core is a collections-and-globals CMS. Optional and vendor-specific features, such as error monitoring with Sentry or an OpenAPI spec of the REST API, are plugins: you install a package and register it in one array.

          import { config, localDisk } from "@cms/config";
import { openapi } from "@cms/openapi";
import { redirects } from "@cms/redirects";
import { sentry } from "@cms/sentry";

export default config({
  entities: [posts],
  roles: [admin],
  storage: localDisk({ root: "./uploads" }),
  plugins: [sentry({ dsn: process.env.SENTRY_DSN }), openapi(), redirects()],
});
        

What is a plugin, and what isn’t

A plugin adds to the CMS in the same shapes you write in cms.config: entities, server routes and public root paths (Contributions). It can also hook into the running CMS: it sets up at boot, observes document changes across entities, hears about errors, log lines and the signed-in editor, on the server and in the admin, and can add Vite plugins to cms build.

A plugin only adds. It never changes your entities, roles or routes.

Fields and components aren’t plugins, even when a package ships them. path() from @cms/paths or a custom input component is used where you need it, in an entity’s fields, and is never registered in plugins. A field made from a plugin instance, like shop.product() from @cms/shopify, is still a plain field, but its input calls the instance’s routes, so it carries the instance’s name (field.plugin) and config() throws when that instance isn’t in plugins.

Storage and email providers aren’t plugins either. Core needs exactly one place to keep asset files and at most one way to send email, so storage (required) and email (optional) are their own keys that take a provider — localDisk() or s3() from @cms/storage-s3, smtp() from @cms/email-smtp or ses() from @cms/email-ses. See Storage and email.

What a plugin is for

The CMS serves editors and delivers content, and a plugin extends that. It isn’t a backend for the people using your site or app:

  • Visitors read, editors write. A public route that answers a cacheable read, like the redirects plugin’s resolve, is fine. Writes made per visitor or per customer, such as wishlists, carts, likes or votes, belong in the app. Content is cached, so a CMS deploy or outage barely shows on the site; a visitor’s write can’t be cached, so it would fail.
  • Don’t relay another service. When the app can call a service directly, a plugin route shouldn’t sit between them on every request. Call the service from the app, and keep the plugin to what editors need from it, like the product picker in @cms/shopify.
  • Entities are for data people manage. A plugin entity suits records editors create, review or browse in the admin. A row per visitor action, a copy of another system’s data, or a report added up from thousands of rows on every page view belongs in an analytics tool or a database the app owns. Core has no retention, aggregation or indexing for that kind of data.

A feature that fails these is usually still worth building, in the app rather than the CMS.

Instance names

Each entry in plugins is an instance, named after its plugin (sentry() is named "sentry"). Pass name to register the same plugin twice, for example to alert two Slack channels with the slackAlerts plugin written below:

          plugins: [
  slackAlerts({ webhookUrl: process.env.TEAM_SLACK_WEBHOOK }),
  slackAlerts({ name: "client-alerts", webhookUrl: process.env.CLIENT_SLACK_WEBHOOK }),
],
        

Names must match /^[a-z0-9-]+$/. Two instances with the same name throw when the config loads.

A plugin built on an SDK with global state can’t run twice. sentry() is one: Sentry’s SDK has one client per process, so a second sentry() fails the boot.

Writing a plugin

definePlugin is public but unstable until 1.0: its hooks may change between releases.

definePlugin(name, create) returns the factory a project calls in plugins. create receives the options (without name) and the instance ({ name }, see Admin pages), and returns the plugin’s hooks, grouped by where they run:

          // lib/slack-alerts.ts
import { definePlugin } from "@cms/config";
import { postToSlack } from "./slack.server";

export const slackAlerts = definePlugin("slack-alerts", (options: { webhookUrl?: string }) => ({
  server: {
    onError: (error, context) => {
      if (context.source !== "request") return;
      void postToSlack(options.webhookUrl, error, context.requestId);
    },
  },
}));
        

Start inline in cms.config.tsx if you like, then move the plugin to its own file or package unchanged. A plugin only one project needs can stay in that project’s repo (Keeping a plugin in your project).

Every key create can return is optional, and a plugin uses only what it needs. The definePlugin reference lists them all in one table.

How a plugin runs

cms.config is evaluated in two places: by the engine in Node, and by the admin in the browser, which bundles it. create runs in both, so it only describes the plugin. Each hook then runs on one side, at a fixed point:

Server boot (cms dev and cms start):

  1. cms.config loads. config() checks every instance: names, entity names, root paths and role names. A clash throws, naming both sources.
  2. server.setup runs for each plugin, in the order plugins lists them. A throw fails the boot, and the plugins already set up get to report it.
  3. The database connects (cms start also checks that every migration is applied), and the storage and email providers are created.
  4. The app is built: plugin entities get their REST endpoints, routes mount under /api/plugins/<instance-name>/, root paths at their exact path.
  5. server.ready runs for each plugin, in order, with content reachable through system. A throw fails the boot.
  6. The server listens.

While it serves:

  • A request to /api/plugins/<instance-name>/<route> runs that route’s handler, after the role check; a root path runs its handler before auth.
  • Every committed write runs the entity’s own after-hooks, then the observers of each plugin whose match selects that entity.
  • Every error the engine reports goes to each plugin’s server.onError, and every warn or error log line to server.onLog.
  • On shutdown, or before the process exits after a crash, server.flush(timeoutMs) gets 2 seconds to send what’s buffered.

In the admin (the browser):

  • /admin/runtime-env.js carries what each plugin’s server.setup returned as admin.
  • Each plugin’s admin.setup runs once with that value. Its onUser and onError wait for it.
  • admin.onUser hears the signed-in editor, and admin.onError the failures the editor didn’t cause. Plugin pages load when they’re opened.

At build time: cms build calls each plugin’s build.vite() and adds what it returns to the admin build. cms dev never calls it.

Contributions

A plugin contributes entities, routes and root paths, written exactly as in cms.config, and admin pages (below). @cms/redirects does all three; simplified, it is:

          // redirects/index.ts
import { definePlugin, type PluginInstance, type PluginInstanceOptions, route } from "@cms/config";
import { z } from "zod";
import type { ImportRow } from "./csv";
import { redirectEntity } from "./entity";
import { importRows, resolve } from "./routes.server";

export const redirects = definePlugin(
  "redirects",
  <const TEntity extends string = "redirects", const TName extends string = "redirects">(
    options: { entity?: TEntity; roles?: string[] } & PluginInstanceOptions<TName>,
    instance: PluginInstance,
  ) => {
    const entityName = (options.entity ?? "redirects") as TEntity;
    return {
      entities: [redirectEntity(entityName)],
      routes: [
        route({
          name: "resolve",
          public: true,
          query: z.object({ path: z.string() }),
          handler: (ctx) => resolve(ctx, entityName),
        }),
        route({
          name: "import",
          method: "POST",
          roles: options.roles,
          body: z.object({ rows: z.array(z.custom<ImportRow>()) }),
          handler: (ctx) => importRows(ctx, entityName),
        }),
      ],
      admin: {
        routes: [
          {
            path: "import",
            label: "Import redirects",
            roles: options.roles,
            component: () =>
              import("./import-page").then(({ importPage }) => ({
                default: importPage({ plugin: instance.name }),
              })),
          },
        ],
      },
    };
  },
);
        

Entities are ordinary entities. They get migrations, REST endpoints, admin screens and @cms/client types like your own, and a role grants access to them in its permissions by name. They are added after your entities.

Routes take the same shape as the routes you write, role checks and query/body schemas included, and mount under the instance name: /api/plugins/<instance-name>/<route>. Two instances never share a URL, and neither a plugin nor a future core route can take yours. A plugin can’t know the project’s role names, so a route anyone may call, like resolve above, sets public: true instead of listing roles. Write each with route(), so a project’s typed client gets its query, body and answer (below).

The instance name in types. TName above, declared through PluginInstanceOptions<TName> and defaulting to the plugin’s name, keeps the instance name literal, so a project’s client knows the routes at /plugins/redirects/resolve, or /plugins/legacy/resolve for redirects({ name: "legacy" }). Without it the name is typed string, and a client accepts the routes under any name: /plugins/${string}/resolve. Set the default to the plugin’s own name.

Root paths are for widely followed conventions that must live at a fixed URL, such as /openapi.json, /robots.txt or /.well-known/security.txt. Each one is an exact path (never a prefix) answering GET, and it runs before auth, so anyone can call it. @cms/openapi serves /openapi.json and /docs this way. Without a plugin claiming /robots.txt, the engine serves one that disallows all crawlers.

          root: [{ path: "/robots.txt", handler: () => new Response("User-agent: *\nAllow: /\n") }],
        

Route and root handlers receive the server context, with the resolved config (every plugin’s entities included) as config. Root paths run before auth, so they get only req, config and system. Put their code in a *.server.ts file (below).

Entity names and collisions

Entity names share one namespace (they are table names and /api/<entity> URLs), so a plugin that contributes entities should let the project choose their names, as redirects does with its entity option. That also lets a project register the plugin twice:

          plugins: [redirects(), redirects({ name: "redirects-eu", entity: "redirects_eu" })],
        

A generic create, as above, keeps the chosen name a literal type, so @cms/client types still know the entity. Declare it with const and cast the name to it.

config() throws when a name is taken, and names both sources:

          Entity name "redirects" is defined by both cms.config and plugin "redirects"
        

It also throws on:

  • an entity named custom or plugins, which would collide with /api/custom and /api/plugins
  • a root path that equals or sits under a core path (/api, /admin, /healthz), or that another plugin already claimed
  • a root path that isn’t exact: wildcards, :params, . or .. segments and trailing slashes are rejected
  • a plugin route or admin page whose roles names a role the project doesn’t define

Observers

observers are after-hooks (afterCreate, afterUpdate, afterPublish, afterUnpublish, afterDelete) that run for every entity the plugin’s match selects, after the entity’s own hooks. An audit log that records every change into an entity of its own:

          // audit/index.ts
import { definePlugin, entity, text } from "@cms/config";
import { recordChange } from "./record.server";

export const audit = definePlugin("audit", (options: { entity?: string }) => {
  const logEntity = options.entity ?? "audit_log";
  return {
    entities: [
      entity(logEntity, {
        fields: [text("entity"), text("documentId"), text("action"), text("userId")],
      }),
    ],
    observers: {
      // Default: every entity but the built-ins. Leave the log out too, so an editor's own edit to
      // it isn't logged.
      match: (target) => target.name !== logEntity && !target.name.startsWith("_"),
      afterCreate: (document, context) =>
        recordChange(logEntity, "create", String(document.id), context),
      afterUpdate: (document, context) =>
        recordChange(logEntity, "update", String(document.id), context),
      afterDelete: (id, context) => recordChange(logEntity, "delete", id, context),
    },
  };
});
        
          // audit/record.server.ts
import type { ObserverContext } from "@cms/config";

export async function recordChange(
  logEntity: string,
  action: string,
  documentId: string,
  { entityName, system, user }: ObserverContext,
) {
  await system.create(logEntity, { entity: entityName, documentId, action, userId: user?.id ?? null });
}
        

One function serves every matched entity, so context.entityName says which one changed, and user and role say who changed it. The write to the log runs other plugins’ observers but never the audit plugin’s own, so it can’t loop. Observers run after the write commits, and a throw is logged and reported without failing the editor’s save. See Hooks → Plugin observers for the exact timing, and why plugins get no before-hooks.

logEntity is a plain string here, so @cms/client can’t type the log’s documents. To type them, declare create generic over the name, as in Entity names and collisions.

Server context

A plugin’s routes, observers and server.ready read and write content through the context they receive, never through tables. @cms/redirects’ resolve route, simplified:

          // redirects/routes.server.ts
import { type Client, type CmsConfig, type RouteContext, routeError } from "@cms/config";
import type { redirectEntity } from "./entity";

// Typed for the one entity the plugin defines.
type RedirectsClient = Client<CmsConfig<readonly [ReturnType<typeof redirectEntity<string>>]>>;

export async function resolve({ req, system }: RouteContext, entityName: string) {
  const from = new URL(req.url).searchParams.get("path") ?? "";
  const { data } = await (system as unknown as RedirectsClient).find(entityName, {
    filter: { from },
    fields: { to: true, status: true },
  });
  if (!data) return routeError(404, "NOT_FOUND", "No redirect for this path");
  return Response.json({ data: { to: data.to, status: Number(data.status) } });
}
        

system and cms are typed for any project, since a plugin never knows the project’s config. It does know the entities it defines, so it can type its calls on them with a Client over a config of just those, cast through unknown as above. data.to is then a string, and a field the entity doesn’t have is a type error. Leave calls on entities the plugin only observes or receives by name untyped.

  • system has full access, and on an entity with drafts its reads return published documents only unless the call passes draft: true. Observers, server.ready and root paths have only system, since no one is calling.
  • cms acts as the caller (routes, and a project’s hooks), so it can only do what their role allows.
  • logger tags each line with the plugin’s instance name, and reportError hands a failure to error-monitoring plugins with the plugin’s name.
  • db is the raw Drizzle database. It is unstable: prefer system.
  • email sends an email through the project’s provider (see ctx.email). Plugins send their own emails this way; the login code email is the project’s to change.

Calls run in-process through the same code path as the REST API, so validation, versions, translations, hooks and other plugins’ observers all apply. A write an observer makes doesn’t re-trigger the observers of any plugin already in that chain, so a plugin can’t loop on its own writes or bounce them off another plugin. See Hooks → Hook context for the full context and the errors a call throws.

Acting as the caller

A route that hands content to whoever calls it reads through cms, so the caller gets exactly what their role may read over REST, and never more. An export route, simplified:

          // export/routes.server.ts
import { type RouteContext, isClientError, routeError } from "@cms/config";
import { toCsv } from "./csv";

export async function exportCsv({ req, cms }: RouteContext) {
  const entityName = new URL(req.url).searchParams.get("entity") ?? "";
  try {
    const { data } = await cms.list(entityName, { limit: 100 });
    return new Response(toCsv(data), { headers: { "Content-Type": "text/csv" } });
  } catch (error) {
    // A role that can't read the entity gets the same 403 as over REST.
    if (isClientError(error)) return routeError(error.status, error.code, error.message);
    throw error;
  }
}
        

A failed call throws ClientError. Check for it with isClientError(error), not instanceof: cms.config loads its own copy of @cms/config, so the class differs from the engine’s.

Reporting a failure you handle

The engine reports what a handler throws: the caller gets a 500, and every plugin’s server.onError hears about it. A Response the handler returns is never reported, even a 5xx. When a route answers a failure itself, hand it to reportError so error monitoring still sees it:

          // newsletter/routes.server.ts
import { type RouteContext, routeError } from "@cms/config";

export async function subscribe({ req, reportError }: RouteContext, apiKey: string) {
  const { email } = (await req.json()) as { email?: string };
  const answer = await fetch("https://api.newsletter.example/subscribers", {
    method: "POST",
    headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
    body: JSON.stringify({ email }),
  });
  if (!answer.ok) {
    reportError(new Error(`Newsletter API answered ${answer.status}`));
    return routeError(502, "UPSTREAM_ERROR", "Couldn't subscribe you right now. Try again later.");
  }
  return Response.json({ data: { subscribed: true } });
}
        

reportError reaches server.onError with source: "reported" and the plugin’s name.

Server hooks

Hook When it runs
setup({ mode, logger }) Once at boot (mode is "dev" or "start"), right after the config loads and before the database connects, so error-monitoring plugins are live for the rest of the boot. A throw fails the boot.
ready(ctx) Once at boot, after the database is connected and the app is built, before the server listens. ctx is the server context with mode, so it can read and write content through system, for example to seed a settings global. A throw fails the boot.
onError(error, context) Every failure the engine reports: errors thrown out of a request (answered with a 5xx), failed after-hooks, unhandled rejections, uncaught exceptions, boot failures, and what server code passes to reportError. context has the source and, inside a request, its requestId, method, path, userId and role.
onLog(record) Every warn and error log line, as { level, message, attributes }. Only allowlisted fields, with addresses and URL credentials redacted.
flush(timeoutMs) On shutdown, and before the process exits after an uncaught exception.

Plugins run in the order they’re listed. setup and ready are part of the boot, so a throw stops it. onError, onLog and flush are isolated: one that throws or rejects is logged and skipped, and the other plugins still run.

ready: work that needs content

setup runs before the database connects; ready runs once it has, before the first request. Use it for content the plugin needs to exist, such as defaults for a settings global it defines. Make it idempotent, since it runs on every boot:

          // maintenance/index.ts
import { boolean, definePlugin, entity, text } from "@cms/config";
import { seedDefaults } from "./seed.server";

export const maintenance = definePlugin(
  "maintenance",
  (options: { entity?: string; message?: string }) => {
    const entityName = options.entity ?? "maintenance";
    return {
      entities: [
        entity(entityName, { global: true, fields: [boolean("enabled"), text("message")] }),
      ],
      server: {
        ready: (ctx) => seedDefaults(ctx, entityName, options.message ?? "We'll be back shortly."),
      },
    };
  },
);
        
          // maintenance/seed.server.ts
import type { PluginServerReadyContext } from "@cms/config";

export async function seedDefaults(
  { system, logger }: PluginServerReadyContext,
  entityName: string,
  message: string,
) {
  const { data } = await system.get(entityName);
  if (data?.message) return;
  await system.update(entityName, { enabled: false, message });
  logger.info("seeded the maintenance message");
}
        

ready has system and no cms, since no one is calling. It writes through the same code path as the REST API, so validation, hooks and other plugins’ observers apply. A boot where ready throws doesn’t start, so let a failure that shouldn’t block the CMS go to logger instead of throwing.

onLog and flush: shipping logs elsewhere

onLog receives every warn and error line the engine logs, already reduced to safe fields. flush is the last chance to send what’s buffered. Together they forward logs to an external service:

          // log-drain/index.ts
import { definePlugin } from "@cms/config";
import { drain, enqueue } from "./drain.server";

export const logDrain = definePlugin("log-drain", ({ url }: { url?: string }) => {
  if (!url) return {}; // no URL, no hooks: the plugin stays off
  return {
    server: {
      onLog: (record) => enqueue(url, record),
      flush: (timeoutMs) => drain(url, timeoutMs),
    },
  };
});
        
          // log-drain/drain.server.ts
import type { PluginLogRecord } from "@cms/config";

let pending: PluginLogRecord[] = [];

export function enqueue(url: string, record: PluginLogRecord) {
  pending.push(record);
  if (pending.length >= 50) void drain(url, 5000);
}

export async function drain(url: string, timeoutMs: number) {
  if (pending.length === 0) return;
  const batch = pending;
  pending = [];
  await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(batch),
    signal: AbortSignal.timeout(timeoutMs),
  });
}
        

onLog must not block: queue the line and return. When an onLog hook throws, the failure is logged but never handed back to onLog, so a broken drain can’t loop.

Admin hooks

Hook When it runs
setup({ data }) Once when the admin boots. The other admin hooks wait for it, and are skipped if it throws.
onError(error, context) Render errors, and failed queries and mutations, except 4xx answers the editor already sees. context has the source ("render", "query", "mutation") and the API’s requestId.
onUser(user) The signed-in editor ({ id, role }), or null after logout.

cms.config is bundled into the admin, and every process.env read in it is undefined there. So an option read from process.env is undefined in the admin, while one written in the config as a literal is bundled with it. Runtime values reach the admin through the server: whatever server.setup returns as admin is passed to admin.setup as data.

          server: {
  setup: () => ({ admin: { endpoint: options.publicEndpoint } }),
},
admin: {
  setup: async ({ data }) => {
    if (!data) return;
    const { startWidget } = await import("./widget");
    startWidget(data);
  },
},
        

data is served in /admin/runtime-env.js, which anyone can load, so hand over only what’s safe to make public. Keep secrets out of the admin bundle: pass them as options from process.env, or read them inside a *.server.ts file (below), never as literals in cms.config.

Admin pages and sidebar

admin.routes adds pages to the admin, in the same shape as the project’s admin.routes. A plugin’s pages mount under its instance name, at /admin/plugins/<instance-name>/<path>, so two instances never share a page:

          admin: {
  routes: [
    {
      path: "import",
      label: "Import redirects",
      roles: options.roles,
      component: () =>
        import("./import-page").then(({ importPage }) => ({
          default: importPage({ plugin: instance.name }),
        })),
    },
  ],
},
        

The page code loads only when the page is opened, and cms.config never loads it in Node, so component must be a () => import(). A page that calls its plugin’s own routes needs the instance name they mount under, which create receives as instance.name; above, it’s passed to the page, which posts to /plugins/${plugin}/import with client from @cms/admin/page (below). See Admin Extensibility → Pages for what a page can import.

admin.deleteActions adds controls to every document’s delete dialog, after the project’s own, in the same shape as the project’s admin.deleteActions. @cms/redirects uses it for Leave a redirect.

admin.documentBanners adds notices above a document’s fields, after the project’s own, in the same shape as the project’s document banners. Give them the plugin’s roles when they call the plugin’s routes, so they show only to the roles those routes let in. @cms/shopify uses it. Plugins don’t add dashboard widgets: the dashboard belongs to the project, and a plugin’s status goes on its own page.

Default sidebar. Plugins sit in one collapsible Plugins group, after the project’s Globals. Inside it, each plugin with pages or entities gets its own group, labeled with its instance name: its pages first, then its entities. A plugin that is one page or one entity and nothing else (@cms/shopify, or @cms/redirects without its import page) shows that item on its own, named after the instance when two instances would read the same. The Plugins group is left out when no plugin has anything to show. Plugin entities stay out of the project’s Entities and Globals groups, and out of the dashboard’s recent activity.

Custom sidebar. A project that writes admin.sidebar gets nothing injected. It places plugin items with the plugin(name) and plugins({ except }) builders, with item(entityName) for a single entity, or with page(path, { plugin: name }) for a single page, wherever it belongs:

          sidebar: ({ builtins, group, item, page, plugin, plugins }) => [
  builtins.DASHBOARD,
  group("Content", {
    children: [item("posts"), page("store", { plugin: "shopify", label: "Shopify" })],
  }),
  plugin("redirects"),
  ...plugins({ except: ["redirects", "shopify"] }),
  builtins.ASSETS,
],
        

cms dev warns about every plugin page and entity the custom sidebar leaves out:

          admin.sidebar doesn't place plugin "redirects" page "import", plugin "redirects" entity "redirects". …
        

The check resolves the sidebar once per role that can use the admin (adminPanel), with a placeholder user that has that role (email placeholder@example.com), and counts an item placed if any role’s sidebar places it. A sidebar that branches on something other than role, such as user.email, is only seen down the placeholder’s branch, so the warning can name an item that some users do see.

Plugin items are filtered by role like the rest of the sidebar: a page shows for roles that can open it, an entity for roles that can read it.

Build hooks

build.vite() runs in cms build only, never cms dev. It returns Vite plugins to add to the admin build, and sourcemap: "hidden" when it needs source maps (for example, to upload them).

Keeping server code out of the admin

cms.config is bundled into the admin, and a plugin is imported by it, so every plugin ships to the browser. Put code that should only run in Node — an SDK, anything holding a secret, route handlers, the build hook’s Vite plugins — in a *.server.ts file. The admin build replaces it with a stub (see Server-only code), and the server and build hooks, which never run in the browser, can call it freely.

A plugin’s create runs in the admin too, so it must not call a *.server.ts function while it builds the plugin, for example to make an observer from a helper (afterPublish: makeLogger("publish")). That calls the stub and the admin fails to load. Pass the function, or call it inside the hook body: afterPublish: (document, context) => logPublish(document, context).

Load heavy SDKs with import() inside setup, as @cms/sentry does, so a plugin that is switched off (no DSN) doesn’t load them at all, in Node or in the admin.

Calling a plugin’s routes

A plugin route is plain HTTP at /api/plugins/<instance-name>/<route>, so anything can call it. The caller needs what the route’s roles ask for (an API key or a signed-in editor), unless the route is public.

From a website or app, use the client’s route, typed from your config. The path, the method, query and body are checked against the route, and the answer is typed from its routeJson():

          import { createClient } from "@cms/client";
import type cmsConfig from "./cms.config";

const cms = createClient<typeof cmsConfig>({ url: "https://cms.example.com" });

const { data } = await cms.route("/plugins/redirects/resolve", { query: { path: "/old-page" } });
// data: { to: string; status: number }
        

A non-2xx answer throws ClientError with the route’s status and code. See cms.route().

From the plugin’s own admin page, use client from @cms/admin/page, which is signed in as the editor, and the instance name create received, so the page works under any name. That client is typed for any config, so give it this plugin’s routes:

          import { client } from "@cms/admin/page";
import type { Client, CmsConfig } from "@cms/config";
import type { redirects } from "./index";

type RedirectsClient = Pick<
  Client<CmsConfig<readonly [], readonly [], readonly [ReturnType<typeof redirects>]>>,
  "route"
>;

const { data } = await (client as unknown as RedirectsClient).route(`/plugins/${plugin}/import`, {
  method: "POST",
  body: { rows },
});
        

From the plugin’s own server code, don’t go over HTTP: call the function the route calls.

Keeping a plugin in your project

A plugin doesn’t have to be a package. When a feature belongs to one project, such as a report on that project’s data or an integration with a service only it uses, keep the plugin in the project’s repo, next to cms.config:

          my-site/
  cms.config.tsx
  plugins/
    store-reports/
      index.ts
      report.server.ts
      overview-page.tsx
        
          // plugins/store-reports/index.ts
import { definePlugin, route } from "@cms/config";
import { loadReport } from "./report.server";

export const storeReports = definePlugin(
  "store-reports",
  (options: { roles?: string[] }, instance) => ({
    routes: [route({ name: "report", roles: options.roles, handler: (ctx) => loadReport(ctx) })],
    admin: {
      routes: [
        {
          path: "overview",
          label: "Store reports",
          roles: options.roles,
          component: () =>
            import("./overview-page").then(({ overviewPage }) => ({
              default: overviewPage({ plugin: instance.name }),
            })),
        },
      ],
    },
  }),
);
        
          // cms.config.tsx
import { config } from "@cms/config";
import { storeReports } from "./plugins/store-reports";

export default config({
  // ...
  plugins: [storeReports({ roles: ["editor"] })],
});
        

It works like a package plugin, with less to set up:

  • No build and no package.json. The plugin is part of the project, so it uses the project’s own copies of @cms/config, @cms/admin and @cms/ui, and there are no peer ranges to keep.
  • Server code follows the same rule. The admin build stubs every *.server.ts file in the project (Keeping server code out of the admin).
  • Admin pages get their CSS. The admin compiles Tailwind classes from the folder that holds cms.config, so keep the plugin inside it. Import from @cms/admin/page and @cms/ui, and add @cms/ui to the project’s dependencies if it isn’t there yet.
  • Routes are typed. The plugin is in your config, so cms.route() types its routes like any other (Calling a plugin’s routes).

Move it to a package when a second project needs it. The code moves unchanged; the next section covers what a package adds.

Publishing a plugin as a package

A plugin in its own file moves to a package unchanged. What changes is how it’s built and which copies of the CMS packages it uses. @cms/redirects is a complete example: an entity, a public route, a POST route and an admin page.

Peer dependencies. List @cms/config as a peer dependency, not a dependency, so the plugin uses the project’s copy: a second copy makes definePlugin’s types and the project’s config disagree. A plugin with admin pages also peers on @cms/admin, @cms/ui and react, for the same reason. The plugin contract is unstable before 1.0, so keep the @cms/config range to the versions you tested (x.y.z below stands for the version you built against).

          {
  "name": "cms-plugin-audit",
  "type": "module",
  "exports": {
    ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" }
  },
  "files": ["dist"],
  "peerDependencies": {
    "@cms/config": "~x.y.z"
  }
}
        

Build. Publish ES modules, and keep every server-only module a file of its own whose name ends in .server.js: that suffix is how the admin build knows to stub it. With tsdown, build with unbundle: true, which keeps one output file per source file:

          // tsdown.config.ts
import { defineConfig } from "tsdown";

export default defineConfig({
  entry: ["src/index.ts"],
  unbundle: true,
  format: ["esm"],
  dts: true,
});
        

A bundled build merges audit.server.ts into index.js, and the SDK it loads then ships to the browser. See Hooks → Server-only code for the rules the stub follows.

Admin pages. Import only from @cms/admin/page (PageLayout and client), @cms/admin/fields (DetachedForm, fields with no document behind them) and @cms/ui, never from the main @cms/admin entry. Keep component a () => import() so the page stays a chunk of its own. Use Tailwind classes freely: the admin compiles the classes of every package the project depends on that depends or peers on @cms/admin or @cms/ui, which a package with pages does anyway. Tailwind never scans node_modules on its own, so a package without either gets no CSS for a class only it uses.

Names. The name you pass definePlugin is the default instance name, and it’s what projects place with plugin(name) in a custom sidebar. Let projects rename any entity you contribute (Entity names and collisions).

Previous

Deployment

Next

Blocks