Developers

Site Code

Hooks, content types and background jobs

Filters and events, your own content types and fields, site members, sending email, calling outside APIs, secrets, cron jobs, webhooks and admin pages

9 min readLast updated

View as Markdown

On this page

Filters and events#

// change a post's content HTML
site.filter('post.content', (html, { post }) => html + '<p class="sig">Thanks for reading</p>', { priority: 20 });

// check before a post is saved — return { error } to refuse
site.filter('post.beforeSave', (p) => p.title === 'x' ? { error: 'This title is not allowed' } : { ...p, excerpt: p.excerpt || p.title });

// your own hooks (Site Code names start with site.)
site.on('site.orderPaid', (data) => log.info('paid', data.id));
site.emit('site.orderPaid', { id: 7 });   // inside a handler, delivered async
Core filterValueUsed by
post.contentThe content HTMLThe post content element
post.beforeSave{type, title, slug, status, excerpt, content, meta}Every way a post is saved
page.head / page.metatitle, description, canonical, og…The <head> of designed pages
collection.itemsThe itemsAfter a collection loads
action.input / action.resultinput / resultAround site.action
mail.beforeSend{to, subject, html, text, replyTo}Before email is sent (null = cancel)
sitemap.urls / robots.txtURL list / text/sitemap.xml, /robots.txt

System events: post.published, post.saved, post.deleted, user.created, media.uploaded, plus plugin events such as form.submitted from the Forms plugin — handlers run after the event, at most 10 seconds each.

Content types and fields#

site.postType('event', {
  label: { th: 'อีเวนต์', en: 'Events' }, icon: '📅', slug: 'events',
  fields: {
    date: { type: 'datetime', required: true, label: { th: 'วันที่', en: 'Date' } },
    place: 'text',
    seats: { type: 'number', min: 0 },
  },
  access: { edit: ['editor', 'author'] },
});
site.fields('post', { readingTime: 'number' });   // add a field to posts
  • An Events menu appears in the admin's content group right after publishing; the fields are in the editor's More fields section
  • On the site: /events/<slug> (choose the template under Site settings → Display → Content types from code) and the archive /events
  • In the designer use {{post.meta.date}}; in code db.posts.list({ type: 'event', where: { 'meta.date': { gte: '2026-01-01' } }, orderBy: '-meta.date' })
  • Field types: text, textarea, number, bool, date, datetime, select, url, image, email, json
  • Removing a type from the code: its posts stay in the database but are hidden until the type is declared again

Write content from code with db.posts.create(post), db.posts.update(id, patch), db.posts.delete(id) (checking the caller's rights like the admin does), or wrap them in db.asSystem(() => …) to use system rights (recorded in the audit).

Since CMS 2.0.5 JavaScript plugins can declare content types too (scope post-types, ids like <plugin id>_<name> e.g. docs_doc, and public: false to serve the pages themselves) — see JavaScript plugins. Site Code can use any id that doesn't clash with an active plugin's type (a clash = cannot publish) and can use public: false as well.

Site members (site.visitor)#

The CMS has no built-in members — your code says who the visitor is:

site.visitor(({ request }) => {
  const s = request.cookies.sid && db.table('member_sessions').where('id', crypto.hash('sha256', request.cookies.sid)).first();
  return s ? { id: s.member_id, name: s.name, groups: ['member', s.tier] } : null;
});
site.visitorGroups(['member', 'gold']);

Then use access: ['group:member'] on routes/collections/actions and visitor.is.member in designer conditions (the code's cookies are pl_site_*, set with response.setCookie(...)).

Email, outside APIs and secrets#

mail.send({ to: '[email protected]', subject: 'New order', html: '<p>…</p>' });   // uses the site's SMTP

const res = http.fetch('https://api.example.com/rates', { timeout: 5000 });     // https only, timeout in milliseconds
const rates = res.json();

const key = site.settings('paymentKey');                                         // from Secrets & settings
  • Email: at most 20 recipients per send and 100 emails/hour (configurable) — during development SITE_CODE_MAIL_SINK=log writes to the log instead of sending
  • http.fetch: the domain must be on the allow list (Secrets & settings), no internal IPs, answers up to 5 MB, at most 10 seconds
  • Secrets are encrypted with AES-256-GCM using SITE_CODE_SECRET_KEY (or the site-code.key file) — they are never shown back in the admin

Background jobs and cron#

site.job('sendNewsletter', { timeout: 300, retries: 3 }, ({ data, progress }) => { progress('50%'); });
jobs.enqueue('sendNewsletter', { subject: 'x' }, { delay: '10m', key: 'oct' });  // returns the job id
site.cron('0 8 * * *', 'sendNewsletter');                                       // daily at 8 am (site time zone)
site.cron('*/15 * * * *', () => db.table('carts').where('expired', true).delete());

View the queue, cancel, retry and run a cron right away on the Background jobs tab. Failed jobs retry with increasing delays until retries is used up.

Incoming webhooks#

site.route('POST /hooks/pay', { access: ['*'], rawBody: true, maxBody: 65536 }, ({ request }) => {
  const ok = crypto.timingSafeEqual(crypto.hmac('sha256', site.settings('paySecret'), request.rawBody), request.headers['x-signature'] ?? '');
  if (!ok) return { status: 401, body: 'bad signature' };
  // …
  return { received: true };
});

Admin pages#

site.adminPage('orders', {
  label: { th: 'ออเดอร์', en: 'Orders' }, icon: '🧾', access: ['editor'],
  render: ({ query }) => ({
    title: 'Orders',
    html: `<header class="ak-page-head"><h1>Orders</h1></header>
           <button class="ak-btn" onclick="anasaki.call('ship', {id: 1}).then(r => AK.toast(r.message))">Ship</button>`,
  }),
});

The page is shown in a sandboxed iframe with the ak-* UI kit and window.AK (tables, charts, toasts etc.) — details in Plugin API.