Write a Plugin
A plugin keeps one feature in one place: its collections, hooks, routes and admin pieces. This recipe writes a small plugin in your project, then shows what else a plugin can define and how to publish one on npm.
Before you start
- Read Plugins for how a site uses a plugin.
- The example plugin uses every option once. Its source is a good model to copy.
A first plugin
This plugin adds an announcements collection and a public route that returns the active announcement.
Define the plugin
A plugin is a function that returns definePlugin(). The function takes the plugin's options:
import { defineCollection, definePlugin } from "tenoncms";
export function AnnouncementsPlugin() {
return definePlugin({
name: "announcements",
collections: {
announcements: defineCollection({
titleField: "text",
fields: {
text: { type: "text", required: true },
active: { type: "boolean" },
},
}),
},
publicRoutes: (api) =>
api.get("/current", async (c) => {
const current = await c.var.cms.findOne("announcements", { where: { active: true } });
return current ? c.json(current) : c.notFound();
}),
});
}
nameis lowercase letters, digits and-. It prefixes the routes: this one answers at/_tenon/announcements/current.publicRoutesrun without a session, soc.var.cmshas no user, and the access rules deny writes.
Add it to the config
import { defineCms } from "tenoncms";
import { AnnouncementsPlugin } from "./cms/plugins/announcements";
export default defineCms({
// ...
plugins: [AnnouncementsPlugin()],
});
Start the dev server. The admin lists Announcements in the sidebar.
Read it
The collection is typed like your own, so server code reads it directly:
const current = await cms.findOne("announcements", { where: { active: true } });
A site on another origin calls the route:
const current = await client.request("/announcements/current");
Install a default
A plugin's seed runs the first time the plugin starts on a database, also on one that has content. Use it to install defaults:
return definePlugin({
name: "announcements",
// ...
seed: async ({ cms }) => {
await cms.create("announcements", { text: "Welcome to the new site", active: false });
},
});
A plugin that is removed and added again does not seed again.
To add an input, a page or an admin bar item, import browser code from a .client.ts module, as in your own config. See Custom fields and Build a custom field.
What a plugin can define
A plugin's additions merge before yours, in the order of plugins. See Plugins for a more information.
Publish it
A plugin on npm is an ordinary package with two halves: the server half from definePlugin(), and the browser half behind its clientRef() calls.
{
"name": "cms-plugin-quotes",
"type": "module",
"exports": {
".": { "types": "./dist/index.d.mts", "default": "./dist/index.mjs" },
"./admin": { "types": "./dist/admin/index.d.mts", "default": "./dist/admin/index.mjs" },
"./admin/bar": { "types": "./dist/admin/bar.d.mts", "default": "./dist/admin/bar.mjs" }
},
"files": ["dist"],
"peerDependencies": { "tenoncms": "^0.28.0" }
}
The build uses tsdown, @tsdown/css, and unplugin-vue for Vue components. Every published plugin MUST get these right:
tenoncmsis a peer dependency and stays external. A bundled copy gives the host two copies of core, which breaksclientRef()and the types.tenoncms/adminis the only core import the browser half needs.- Ship the browser half compiled. The host's build does not compile
.vue, JSX or TypeScript fromnode_modules. Bundle Vue or React into the admin chunks, as above, or write plain DOM. The host then installs no extra package. clientRef()takes a package path, as a literal string.clientRef("cms-plugin-quotes/admin#mountStats")resolves from the host's project root, so the host installs the plugin there. The adapters find the call by reading the module graph oftenon.config.ts, so the config MUST import the plugin statically.- Give the admin bar its own entry. The bar loads on every page of the site. Everything it reaches MUST be free of CSS and of Vue
<style>blocks, and the bar's shadow root gets no page CSS. Keep the bar mounts in a file likeadmin/barand style them inline. The adapters reject a plugin that breaks this at startup. - Scope the plugin's CSS. The admin's Tailwind does not scan plugin code, and plugin CSS applies to the whole admin. Scope every selector: a page class, scoped styles or a Tailwind
prefix(). See Styles and UI libraries. - Build the types.
definePlugin()keeps the collection and global names, so the host getscms.find("quotes")typed.
Before you publish, run npm pack, install the tarball in a test site and start its dev server once. A wrong exports entry, a bundled copy of tenoncms or CSS in the bar's graph shows up there.
Import browser code instead of clientRef()
A plugin in your project imports .client.ts modules like your config does. A published plugin builds its server and browser halves apart, so its server build needs clientModules() from tenoncms/vite. It turns the imports into clientRef() calls with the package path:
import { clientModules } from "tenoncms/vite";
const serverPlugin = clientModules({
root: import.meta.dirname,
server: true,
references: { "./src/stats.client.ts": "cms-plugin-quotes/admin" },
});
- Add
serverPluginto thepluginsof the server build only. Never useserver: truein the browser build. - Map every browser module that the server build reaches. A module without an entry would point into the host's project.
- Build
src/stats.client.tsas the browser entry behind the./adminexport, and ship the types of both halves.
Plain clientRef() calls need no extra build step.
Related resources
- Plugins: use a plugin, and the bundled plugins.
- Customization:
.client.tsmodules andclientRef(). - Custom pages and actions: the admin pages a plugin adds.
- Jobs: tasks and schedules.
- Lifecycle hooks:
seedand the other start hooks.