Plugins
Plugin example — a guestbook
Build a complete JavaScript plugin step by step — a data table, a public page inside the site's header and footer, a message form, email notifications, an admin page and settings
On this page
This example builds a Guestbook plugin (guestbook): visitors write messages at /guestbook, and administrators get an email notification and can delete messages from the admin. It uses only the public API — read the basics first in JavaScript plugins.
1. Layout#
guestbook/
├── manifest.json
├── README.md
├── code/main.ts
└── migrations/001_create_entries.ts
2. manifest.json#
{
"id": "guestbook",
"name": "Guestbook / สมุดเยี่ยม",
"version": "1.0.0",
"description": "สมุดเยี่ยมให้ผู้เยี่ยมชมเขียนข้อความ / A simple guestbook",
"author": "Your name",
"icon": "📖",
"category": "content",
"license": "MIT",
"minCore": "2.0.4",
"runtime": "js",
"permissions": ["code", "settings"],
"settings": [
{ "key": "title", "type": "text", "default": "Guestbook", "maxLength": 100,
"label": { "th": "หัวข้อหน้า", "en": "Page title" } },
{ "key": "notify", "type": "boolean", "default": true,
"label": { "th": "ส่งอีเมลแจ้งเมื่อมีข้อความใหม่", "en": "Email me on new entries" } }
],
"code": {
"entry": "code/main.ts",
"scopes": ["db", "routes", "mail", "admin-pages"],
"routes": ["/guestbook"]
}
}
Permissions asked for: db (its own table), routes (the /guestbook page), mail (notifications + reading the administrator email), admin-pages (the admin page).
3. Migration#
// migrations/001_create_entries.ts → the real table p_guestbook_entries
export default migration({
up(schema) {
schema.create('entries', (t) => {
t.id();
t.string('name', 80);
t.text('message');
t.timestamps();
});
},
down(schema) { schema.drop('entries'); },
});
4. The code (code/main.ts)#
const esc = (s: unknown) => String(s ?? '').replace(/[&<>"']/g, (c) =>
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' } as Record<string, string>)[c]);
/** application/x-www-form-urlencoded → { key: value } */
function parseForm(body: string): Record<string, string> {
const out: Record<string, string> = {};
for (const pair of (body || '').split('&')) {
if (!pair) continue;
const [k, v = ''] = pair.split('=');
out[decodeURIComponent(k.replace(/\+/g, ' '))] = decodeURIComponent(v.replace(/\+/g, ' '));
}
return out;
}
// the public page — shown inside the site's header/footer
site.route('GET /guestbook', { access: ['*'] }, () => {
const title = String(site.settings('title') || 'Guestbook');
const rows = db.table('entries').orderBy('id', 'desc').limit(50).get();
const list = rows.map((r) => `<li><strong>${esc(r.name)}</strong><p>${esc(r.message)}</p></li>`).join('');
return {
page: {
title,
html: `<section class="gb"><h1>${esc(title)}</h1>
<form method="post" action="/guestbook">
<input name="name" required maxlength="80" placeholder="Name">
<textarea name="message" required maxlength="1000" placeholder="Message"></textarea>
<button type="submit">Send</button>
</form>
<ul>${list || '<li>No messages yet</li>'}</ul></section>`,
},
};
});
// take the form, then go back to the page
site.route('POST /guestbook', { access: ['*'], maxBody: 8192 }, ({ request }) => {
const f = parseForm(request.body);
const name = (f.name || '').trim().slice(0, 80);
const message = (f.message || '').trim().slice(0, 1000);
if (name && message) {
db.table('entries').insert({ name, message });
const to = site.info().adminEmail;
if (site.settings('notify') && to) {
try {
mail.send({ to, subject: 'New guestbook message', html: `<p><b>${esc(name)}</b>: ${esc(message)}</p>` });
} catch (e) {
log.warn('could not send email', String(e)); // SMTP not set up yet
}
}
}
return { status: 303, headers: { Location: '/guestbook' } };
});
// the action the admin page calls
site.action('delete', {
input: { id: 'number' },
access: ['administrator', 'editor'],
run: ({ input }) => {
db.table('entries').where('id', input.id).delete();
return { message: 'Deleted' };
},
});
// the admin page
site.adminPage('entries', {
label: { th: 'สมุดเยี่ยม', en: 'Guestbook' }, icon: '📖', access: ['administrator', 'editor'],
render: () => {
const rows = db.table('entries').orderBy('id', 'desc').limit(200).get();
const tr = rows.map((r) => `<tr><td>${esc(r.name)}</td><td>${esc(r.message)}</td>
<td><button class="ak-btn" onclick="del(${Number(r.id)})">Delete</button></td></tr>`).join('');
return {
title: 'Guestbook',
html: `<header class="ak-page-head"><h1>Guestbook</h1></header>
<div class="ak-table-wrap"><table class="ak-table"><thead><tr><th>Name</th><th>Message</th><th></th></tr></thead>
<tbody>${tr}</tbody></table></div>
<script>
async function del(id) {
if (!(await AK.confirm('Delete this message?', { danger: true }))) return;
anasaki.call('guestbook:delete', { id }).then(() => location.reload(), (e) => AK.toast(e.message, 'error'));
}
</script>`,
};
},
});
On a plugin's admin page the action name carries the plugin's namespace (guestbook:delete), and anasaki.call returns a Promise that rejects when the action fails. The ak-* classes and AK.confirm / AK.toast come from the admin UI kit the system adds to every page.
5. Install and test#
- Zip the folder:
cd guestbook && zip -r ../guestbook-1.0.0.zip . - Plugins → Upload .zip → check the 4 permissions → Approve and install → Activate (the migration runs now)
- Open
https://your-site/guestbookand send a message - A Guestbook menu appears in the admin — try deleting a message
- Plugins → Guestbook → Settings: change the page title, then refresh
/guestbook - Problems? See Site Code → Logs (the plugin's log lines start with
guestbook:)
6. Going further#
- Let designers place the message list on any page with
site.collection('entries', { … access: ['*'] })and pick it as the data source of a Collection (Binding data to the designer) - Block spam with a honeypot field and count sends per IP with
request.ip - Let other plugins know about new messages: declare
"hooks": { "events": ["guestbook.created"] }and callsite.emit('guestbook.created', { id }) - Ready to share: write a Thai/English README, add images to
screenshots/and publish on the Plugin Store
More examples in the repository: examples/js-plugins/ (thai, promptpay, files, admin-crud, members, money + shop) and the official plugins' sources in plugins-official/.
