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
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:
| Tab | Used for |
|---|---|
| Code editor | The project's files (draft), route testing, upload/download .zip, publish, Safe mode |
| Versions | Published versions (the last 100 are kept) and restore |
| Logs | Output of log.* / console.* and errors with stacks pointing at file:line (kept 7 days) |
| Database | Tables, data, migrations and the SQL console — see The Site Code database |
| Access | Who can call routes / collections / actions / pages / tables (administrators can override the code's values) |
| Secrets & settings | Settings and secrets the code reads with site.settings(), the domains http.fetch may call, email/route limits |
| Background jobs | The job queue and cron schedules |
| Hooks | Every filter / event and its listeners in their real order |
| Formatters | Formatters from code and plugins, and aliases |
Required permissions#
| Permission | Allows |
|---|---|
view_scripts | View files, versions, logs and status |
edit_scripts | Edit/upload files, save drafts, test routes and edit page code blocks in the designer |
publish_scripts | Publish, restore versions, Safe mode — equivalent to an administrator |
manage_scripts | Clear logs, access, secrets, the domain list and limits |
view_code_data / edit_code_data | View / 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#
- Open Site Code and create a
main.tsfile (the entry ismain.ts, elsemain.js,index.ts,index.js) - 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));
- Save — the draft is built at once and errors show with
file:line:column - 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)
- 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
.zipof the whole project (merged with or replacing the current files; review the changes before confirming) and Download all as a.zipwithanasaki.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').urlgives the address with?v=(cached for a year), and code blocks can load them withanasaki.lib('qr')/anasaki.style('base') - Imports are relative paths only (
./x,../lib/y) plus active JavaScript plugins (import { bahtText } from 'thai') — there is nonode_modules, so copy ES module libraries intolib/ - ES2022 is supported (classes, async/await, optional chaining etc.) but there is no
fetch,setTimeout,fs,processorIntl— usehttp.fetchinstead.atob/btoaexist (2.2.0) andtoLocaleString('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#
| What | Limit |
|---|---|
| route / collection / action / page | 2 seconds per call |
| event handler | 10 seconds |
| Concurrency | 8 runs — extra ones wait up to 2 seconds, then get 503 |
| Request body | 1 MB (maxBody up to 5 MB) |
| Circuit breaker | A handler that fails 20 times in 1 minute is disabled for 5 minutes |
| Public routes | 120 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
