The Big Picture

A module is a folder modules/<id>/ whose init.ts exports an AppModule object. It is discovered at startup; from its declaration the core wires up its database tables, public pages, API, admin pages, sidebar entry and settings tab. No core code changes are needed.

KindLocationPurpose
Feature modulemodules/<id>/Functionality shared by every site (products, media, a blog...). This guide.
Site codemodules/site/<site>/init.tsOptional custom code for one site. See How to Create a Site.

isCore: true marks a module that cannot be disabled (users, admin, email, stats...). Leave it false for your own modules.

1. Scaffold the Module

bun run make:module blog

Creates modules/blog/init.ts (schema, a public page, a public API, an admin API, an admin page and a setting) and two template stubs in modules/blog/templates/. Module ids start with a letter and use lowercase letters, digits and dashes; the table name uses underscores instead (blog-posts gets the table blog_posts, as dashes are not allowed in SQL names). Restart the server to load it: bun run dev restarts when a file it already loaded changes, not when a new module folder appears. On a production server, Admin > Modules lists the new folder and has a Restart server button (where a process manager starts the server again; see the overview).

The code is TypeScript in strict mode (bun run lint), with no any: give query results a row type (dbAll<{ id: string; title: string }>(...); untyped rows are Record<string, unknown>), pass SQL arguments as SqlValue[], and write catch (err) with errorMessage(err) from src/core/logger.ts.

2. The Module Object and its Lifecycle

import type { AppModule } from '../../src/core/types.js';
import { dbOne, dbRun } from '../../src/core/db.js';

export const blogModule: AppModule = {
  id: 'blog',                 // must be unique; used in URLs (/api/v1/blog/...)
  name: 'Blog',
  version: '1.0.0',
  description: 'Articles and news.',
  isCore: false,

  // Applied on first startup and again whenever this text changes;
  // use CREATE ... IF NOT EXISTS so re-running is harmless.
  schema: `
    CREATE TABLE IF NOT EXISTS articles (
      id TEXT PRIMARY KEY,
      slug TEXT UNIQUE NOT NULL,
      title TEXT NOT NULL,
      content TEXT,
      status TEXT DEFAULT 'draft',
      created_at INTEGER NOT NULL
    );
  `,

  // Runs at every startup, after the schema: guard it so it seeds only once.
  onSeed: async () => {
    if (await dbOne('SELECT id FROM articles LIMIT 1')) return;
    await dbRun(
      "INSERT INTO articles (id, slug, title, content, status, created_at) VALUES (?, 'welcome', 'Welcome', 'Hello!', 'published', ?)",
      [crypto.randomUUID(), Date.now()]
    );
  },
};

export default blogModule;
HookWhen it runsUse it for
onMigrate(db)Every startup, before schemaChanging existing tables (ALTER TABLE ... ADD COLUMN). Check that the table exists first: on a fresh install it doesn't yet.
schemaWhen its text changes (applied statements are recorded)Creating tables and indexes. Statements are split on ;, so triggers are not supported.
onSeed(db)Every startup, after every module's schemaDefault rows and settings, guarded. Other modules' tables already exist (e.g. Pages creates a widget)
onInit({ app })Every startup, after all modules are set upStartup work (e.g. syncing files, registering helpers that need setup)

3. Public Pages

Routes in site.routes are public pages wrapped in the active theme's layout:

import { renderHtml } from '../../src/core/renderer.js';
import { dbAll, dbOne } from '../../src/core/db.js';
import * as path from 'path';

  site: {
    routes: [
      {
        path: '/blog',
        cacheTtl: 60,             // seconds, anonymous visitors only
        cacheTags: ['blog'],
        handler: async (c) => {
          const posts = await dbAll("SELECT * FROM articles WHERE status = 'published' ORDER BY created_at DESC");
          return renderHtml(c, path.resolve('modules/blog/templates/blog-public.html'), {
            title: 'Blog',
            data: { posts },
          });
        },
      },
      {
        path: '/blog/:slug',
        cacheTtl: 300,
        cacheTags: ['blog'],
        handler: async (c) => {
          const post = await dbOne("SELECT * FROM articles WHERE slug = ? AND status = 'published'", [c.req.param('slug')]);
          if (!post) return renderHtml(c, '404.html', { title: 'Not Found', status: 404 });
          return renderHtml(c, path.resolve('modules/blog/templates/blog-post.html'), { title: post.title, data: { post } });
        },
      },
    ],
  },
  • Templates: a path with a folder (modules/blog/templates/x.html) is a file of your module; a bare name (404.html) is a page of the active theme.
  • Precedence: for the same URL, the active site's init.ts routes win, then the theme's pages (blog.html would win over your /blog), then modules like this one. Modules with isCore: true are mounted first and win over all of these.
  • Caching: cacheTtl caches the rendered page for anonymous visitors; signed-in users always get a fresh page. The cache key includes the visitor's language and the query string (set cacheQuery: false when the page never reads it, so ?utm_source=... links share one entry). Cached pages are cleared when the server starts; clear them when your data changes: cache.invalidateTag('blog'). A page that shows another module's data (through a helper) should add that module's tag to cacheTags.
  • Menu: entries in site.nav (e.g. { label: 'Blog', path: '/blog', order: 10 }) are added to every site's menu while the module is enabled, placed by order after the standard links (Home 0, About 1, Contact 2). A link the site's own menu already has is not repeated.

Handlers return a Response, data for the template, or null for "not mine": the request then goes on to later routes. Routes starting with a parameter (/:slug) are tried after every fixed route, so a catch-all like Pages' /:slug never hides /products or /sitemap.xml.

4. API Routes

Put public JSON endpoints in apiRoutes (served at /api/v1/<id>/*) and admin-only ones in adminApiRoutes (served at /api/v1/<id>/admin/*). The core's admin gate checks every admin route against the user's role (admins always pass; managers and editors need the permission, see below), so handlers never check roles themselves.

import { Hono } from 'hono';
import type { AppEnv } from '../../src/core/types.js';
import { cache, cacheApi } from '../../src/core/cache.js';

  apiRoutes: (() => {
    const api = new Hono<AppEnv>();
    // Public, cached for anonymous visitors for 60 s
    api.get('/posts', cacheApi({ ttl: 60, tags: ['blog'] }), async (c) =>
      c.json({ posts: await dbAll("SELECT id, slug, title FROM articles WHERE status = 'published'") })
    );
    return api;
  })(),

  adminApiRoutes: (() => {
    const adminApi = new Hono<AppEnv>();
    adminApi.post('/save', async (c) => {
      const user = c.get('user')!;          // a staff user holding blog.edit here
      const body = await c.req.parseBody();
      // ... validate, insert or update, record user.userId
      cache.invalidateTag('blog');          // refresh cached pages and API responses
      return c.json({ success: true });
    });
    return adminApi;
  })(),

Every POST/PUT/PATCH/DELETE must carry the CSRF token. Admin page scripts send it as a header: headers: { 'x-csrf-token': window.__CSRF_TOKEN__ }.

5. Admin Pages, Sidebar and Settings

  admin: {
    navItem: { id: 'blog', label: 'Blog', path: '/admin/blog', icon: 'file-text', order: 40 },
    views: [
      {
        path: '/blog',                                   // served at /admin/blog
        title: 'Blog',
        template: 'modules/blog/templates/blog-admin.html',
        handler: async (c, user) => ({ posts: await dbAll('SELECT * FROM articles ORDER BY created_at DESC') }),
      },
    ],
    settingsFields: [
      { key: 'blog_posts_per_page', label: 'Posts per page', type: 'number', defaultValue: 10, min: 1, max: 100 },
      { key: 'blog_comments', label: 'Allow comments', type: 'boolean', defaultValue: false },
    ],
  },
  • Admin pages are protected automatically: they need the blog.view permission (administrators always pass; see Roles & permissions below) and use the admin layout. The handler returns the template's data.
  • icon is a Lucide icon name. The sidebar lists every module's link by order (Pages 7, Users 20, Statistics 50, Widgets 62, Modules 90, Settings 91; the example's 40 lands after Users); add group: 'system' to the nav item for a server tool, which then appears under System (like Server Status).
  • settingsFields become a tab in Admin > Settings. Types: text, number, boolean, textarea, select (with options), checkboxGroup, password. Saving is validated: only the tab's own fields are accepted, numbers must respect min / max, text maxLength (default 1000; textarea 10000), selects and checkbox lists their options. Password values are never sent back to the browser (an empty field keeps the stored one). Read values with await getSetting('blog_posts_per_page', 10), and yes/no settings with await getFlag('blog_comments', false) (they may be stored as true, 1 or '1'). Setting keys are global, so prefix them with your module id.
  • For several groups, declare settingsSections: [{ id, label, icon, description, fields, onSave? }]: each section is its own tab (blog.comments etc.). Text fields may also declare format (email, emails, domains, ips, gaId, timezone) and placeholder; datetime is a date-and-time input. A select can take its choices from optionsProvider instead of options: 'themes', 'locales' or 'timezones' (the saved value is checked against the same list). Lists (emails, domains, IPs) are stored one per line: read them with settingList(await getSetting('key', '')). Format dates for display with (await dateFormatter())(timestamp) (src/core/dates.ts), which follows Settings > General.
  • For list pages, follow the TabulatorJS grid + modal pattern described in the README (DataGrids and Modals).

Roles & permissions

Your module appears in Admin > Users > Roles & Permissions by itself, with view, create, edit, delete unchecked for managers and editors, so it is administrator-only until boxes are ticked. Admin pages need blog.view; admin API GET needs view, DELETE delete, other methods edit. A save route for new and existing records maps to 'save' and checks canSave(c, 'blog', !id) (create for new, edit for existing). Declare permissions for a publish action, routes like POST /delete, or an admin-only module, and use can(c, 'blog.publish') for rules that depend on the data. See Roles & Permissions.

  permissions: {
    actions: ['view', 'create', 'edit', 'delete', 'publish'],
    routes: { 'POST /save': 'save', 'POST /delete': 'delete', 'POST /publish': 'publish' },
  },

Record important actions in the audit log: await audit(c, 'blog.publish', { type: 'post', id, label: title });

6. Share Data with Helpers (optional)

Expose functions other modules and sites can call without importing your module:

import { registerHelper } from '../registry.js';

const blogHelpers = {
  getRecent: async (limit = 5) =>
    dbAll("SELECT slug, title FROM articles WHERE status = 'published' ORDER BY created_at DESC LIMIT ?", [limit]),
};
Object.entries(blogHelpers).forEach(([name, fn]) => registerHelper(`blog:${name}`, fn));

// elsewhere (the caller states the result type; null when no module registered the helper):
//   const recent = (await callHelper<Array<{ slug: string; title: string }>>('blog:getRecent', 3)) ?? [];

See Helper Registry Pattern.

7. Add Data to Every Page (optional)

extendBaseData adds variables to every rendered page, including admin pages. It runs on every render, so keep it fast (no slow queries):

  extendBaseData: async (data, c) => ({ blogEnabled: true }),

7b. Shortcodes for Pages and Templates (optional)

A module can offer embed codes for page content, theme pages and layouts. Declare handlers under shortcodes; render below is written {{ blog:render latest="3" }}:

  shortcodes: {
    render: async (attrs, c) => {
      const posts = await dbAll('SELECT title, slug FROM posts ORDER BY created_at DESC LIMIT ?', [Math.min(20, Number(attrs.latest) || 3)]);
      const html = posts.map((p) => `<a href="/blog/${escapeHtml(p.slug)}">${escapeHtml(p.title)}</a>`).join('');
      return { html, cacheTags: ['blog'] }; // or just the HTML string
    },
  },
  • Attributes arrive as strings (key="value" or key=value); check and limit them: editors write shortcodes.
  • Escape anything that comes from data. The output is finished HTML and is never scanned again (shortcodes inside it are not rendered).
  • cacheTags are added to the cached page, so cache.invalidateTag('blog') after a save refreshes every page showing the embed.
  • An error renders <!-- blog:render failed -->; a disabled module's shortcodes render nothing; text naming a module without that shortcode is left as written.
  • Example: the Collections module's {{ collections:render collection="faq" }} (modules/collections/init.ts).

7c. Public Addresses for the Sitemap and Static Exports (optional)

A module whose public pages live at dynamic routes (/:slug, /blog/:slug) lists them with publicPaths, so sitemap.xml and static exports find them even when no menu or link points to them:

  publicPaths: async () => (await dbAll<{ slug: string; updated_at: number }>(
    "SELECT slug, updated_at FROM posts WHERE status = 'published'"
  )).map((p) => ({ path: `/blog/${p.slug}`, updatedAt: p.updated_at })),

Fixed routes (/blog) are found without it. List published content only; drafts must not appear. An entry is a plain address ('/blog/hello') or { path, updatedAt }: updatedAt (milliseconds) becomes the sitemap's <lastmod>, the day the content last changed. A fixed route can be dated too: list { path: '/blog', updatedAt: newestPost }. Without a date the entry has no <lastmod>.

Moved addresses

When published content gets a new address, call addRedirect(oldPath, newPath, 'post') from src/core/redirects.ts: the old address then answers 301 to the new one (no chains; it appears in Admin > Pages > Redirects). When new content takes an address, call clearRedirectFrom(path) so it is no longer redirected.

Edit link in the site's admin bar

Staff see an admin bar above public pages. To give it an Edit link for what your page shows, pass editLink to renderHtml, after checking the permission (the bar shows it only for addresses under /admin):

  editLink: (await can(c, 'blog.edit')) ? { href: `/admin/blog?edit=${post.id}`, label: 'Edit post' } : undefined,

Your admin page then opens that record when the address has ?edit=<id>.

Structured data and the canonical address

Every public page gets <link rel="canonical"> by itself: APP_URL + the path, without the query string (tracking tags, sorting), except ?page=N of a paged list. To describe a page for search engines, pass jsonLd to renderHtml (schema.org items; an item without url gets the canonical address; use absoluteUrl() from renderer.ts for images):

  return renderHtml(c, path.resolve('modules/blog/templates/post.html'), {
    title: post.title,
    data: { post },
    jsonLd: { '@type': 'BlogPosting', headline: post.title, dateModified: new Date(post.updated_at).toISOString() },
  });

For search results and link previews, pass data.metaDescription (use excerpt(text) from renderer.ts to turn HTML into about 160 characters of plain text) and shareImage (a path such as /uploads/photo.jpg; empty: the site default).

A trail for search results: add breadcrumbs([['Blog', '/blog'], [post.title, c.req.path]]) (Home is added) to jsonLd. Set ogType ('article', 'product') when the page is not a plain web page.

Error pages (any status other than 200) get neither. The home page already carries WebSite and Organization; Pages add WebPage and Products add Product (with price, currency and stock).

7d. Numbers on the Admin Dashboard (optional)

A module can show counts on Admin > Dashboard with dashboardStats. They appear only while the module is enabled and only to users with <module>.view:

  dashboardStats: async () => {
    const row = await dbOne<{ n: number; drafts: number }>(
      "SELECT COUNT(*) AS n, SUM(status != 'published') AS drafts FROM posts");
    return [{ label: 'Blog posts', value: row?.n ?? 0, sub: `${row?.drafts ?? 0} drafts`, href: '/admin/blog' }];
  },

Each entry is one card: label, value, an optional line under it (sub) and the page the card links to (href). Keep the queries cheap: they run on every dashboard visit. An error leaves the card out instead of breaking the dashboard. Examples: Pages, Media, Collections, Products and Users.

8. Enable and Disable

Optional modules can be switched off in Admin > Modules. A disabled module's public pages, API (/api/v1/<id>/*) and admin pages return 404, and its sidebar entry disappears (widget, page and module shortcodes render nothing while their module is off); its tables and data are kept. Modules with isCore: true cannot be disabled.

9. Test It

  • Open https://carnivalcms.com/blog, /admin/blog and /api/v1/blog/posts, and check the module appears in Admin > Modules.
  • Automated tests use bun test against a separate test.db. tests/helpers/app.ts builds the full app and gives you an admin session (createRoleUser('editor') gives a user of any role, to test permissions):
import { test, expect } from 'bun:test';
import { buildApp, adminCookie, post } from '../helpers/app.js';

test('admins can save a post', async () => {
  const app = await buildApp();
  const res = await app.request('/api/v1/blog/admin/save', post(await adminCookie(), { title: 'Hi' }));
  expect(res.status).toBe(200);
});