Developers

Site Code

Site Code — your site's server-side code

Write TypeScript/JavaScript that runs on your site's server (like WordPress's functions.php) — routes, events, your own database, data for the designer — with drafts, testing and safe publishing

9 min readLast updated

View as Markdown

On this page

Site Code is your site's server-side TypeScript / JavaScript. It is stored in the CMS database, bundled with esbuild and run in a sandbox (goja) inside the CMS. Use it for site routes, event listeners, your own tables, data sources for the designer, background jobs, admin pages and more — the same API is used to write JavaScript plugins.

The Site Code page#

Developer → Site Code has these tabs:

TabUsed for
Code editorThe project's files (draft), route testing, upload/download .zip, publish, Safe mode
VersionsPublished versions (the last 100 are kept) and restore
LogsOutput of log.* / console.* and errors with stacks pointing at file:line (kept 7 days)
DatabaseTables, data, migrations and the SQL console — see The Site Code database
AccessWho can call routes / collections / actions / pages / tables (administrators can override the code's values)
Secrets & settingsSettings and secrets the code reads with site.settings(), the domains http.fetch may call, email/route limits
Background jobsThe job queue and cron schedules
HooksEvery filter / event and its listeners in their real order
FormattersFormatters from code and plugins, and aliases

Required permissions#

PermissionAllows
view_scriptsView files, versions, logs and status
edit_scriptsEdit/upload files, save drafts, test routes and edit page code blocks in the designer
publish_scriptsPublish, restore versions, Safe mode — equivalent to an administrator
manage_scriptsClear logs, access, secrets, the domain list and limits
view_code_data / edit_code_dataView / change data in the code database

By default only administrators have them; grant them to other roles under Permissions (Users and permissions).

Your first code: a hello route#

  1. Open Site Code and create a main.ts file (the entry is main.ts, else main.js, index.ts, index.js)
  2. Add the code:
// GET /hello/Somchai → {"hi":"Somchai"}
site.route('GET /hello/{name}', { access: ['*'] }, ({ request }) => ({ hi: request.params.name }));

// plain text
site.route('GET /feed.txt', { access: ['*'] }, () => ({
  status: 200, headers: { 'Content-Type': 'text/plain' }, body: 'ok',
}));

// listen to system events (runs after the event)
site.on('post.published', (post) => log.info('published', post.title, post.url));
  1. Save — the draft is built at once and errors show with file:line:column
  2. Press Test route to run a route of the saved draft in the sandbox (the live site is not affected, but the real database is used)
  3. Press Publish, then open https://your-site/hello/Somchai

The default access is administrators only — use access: ['*'] to let anyone call it, or name role slugs such as ['editor'].

Draft → publish#

  • Save writes to the draft — the live site keeps using the published version
  • Publish builds the draft, checks what it registers, runs pending migrations and stores it as a new version. On any problem the publish is refused and the previous version keeps running
  • Versions → Restore brings an old snapshot back as a new version (optionally replacing the draft too) — restoring does not run migrations' down()
  • Upload a .zip of the whole project (merged with or replacing the current files; review the changes before confirming) and Download all as a .zip with anasaki.d.ts

Project layout#

main.ts          ← the entry point
events.ts        ← import { x } from './events'
lib/format.ts
data.json        ← import data from './data.json'
migrations/001_create_orders.ts
anasaki.d.ts     ← types for the whole API (download / GET /api/v1/code/types)
  • Allowed extensions: .ts .js .mjs .json .md — at most 200 files, 512 KB each, 2 MB in total
  • Static files (2.2.0) — files in the public/ folder (.css .js .mjs .json .svg .txt .xml .webmanifest .md) are not bundled but served at /site-assets/<name> from the published version. site.asset('public/qr.js').url gives the address with ?v= (cached for a year), and code blocks can load them with anasaki.lib('qr') / anasaki.style('base')
  • Imports are relative paths only (./x, ../lib/y) plus active JavaScript plugins (import { bahtText } from 'thai') — there is no node_modules, so copy ES module libraries into lib/
  • ES2022 is supported (classes, async/await, optional chaining etc.) but there is no fetch, setTimeout, fs, process or Intl — use http.fetch instead. atob / btoa exist (2.2.0) and toLocaleString('th-TH') shows Buddhist-era years (2.1.1)

Common APIs#

db.posts.list({ type: 'post', category: 'news', perPage: 10 }); // { items, total }
db.posts.get('hello-world');                                    // by slug or id
cache.set('key', { any: 'json' }, 60); cache.get('key');         // in-memory cache (10 MB)
crypto.uuid(); crypto.hash('sha256', 'data'); crypto.password.hash(pw);
log.info('message', obj);                                        // → Logs

db, cache, crypto, mail, http and jobs work inside handlers only — calling them at the top level of a file (during registration) throws.

Limits and safety#

WhatLimit
route / collection / action / page2 seconds per call
event handler10 seconds
Concurrency8 runs — extra ones wait up to 2 seconds, then get 503
Request body1 MB (maxBody up to 5 MB)
Circuit breakerA handler that fails 20 times in 1 minute is disabled for 5 minutes
Public routes120 calls/minute/IP (configurable)

Published code broke the site? Turn on Safe mode (stops all code on the live site at once), or if the admin is unreachable, set SITE_CODE_DISABLED=true in the container's environment and restart.

Next: edit code in VS Code with the anasaki-code CLI · add your own tables in The Site Code database · add hooks and background jobs in Hooks, content types and background jobs