# 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

Source: https://anasaki.live/docs/en/developers/plugin-example

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](/docs/en/developers/js-plugins).

## 1. Layout

```text
guestbook/
├── manifest.json
├── README.md
├── code/main.ts
└── migrations/001_create_entries.ts
```

## 2. manifest.json

```json
{
  &#34;id&#34;: &#34;guestbook&#34;,
  &#34;name&#34;: &#34;Guestbook / สมุดเยี่ยม&#34;,
  &#34;version&#34;: &#34;1.0.0&#34;,
  &#34;description&#34;: &#34;สมุดเยี่ยมให้ผู้เยี่ยมชมเขียนข้อความ / A simple guestbook&#34;,
  &#34;author&#34;: &#34;Your name&#34;,
  &#34;icon&#34;: &#34;📖&#34;,
  &#34;category&#34;: &#34;content&#34;,
  &#34;license&#34;: &#34;MIT&#34;,
  &#34;minCore&#34;: &#34;2.0.4&#34;,
  &#34;runtime&#34;: &#34;js&#34;,
  &#34;permissions&#34;: [&#34;code&#34;, &#34;settings&#34;],
  &#34;settings&#34;: [
    { &#34;key&#34;: &#34;title&#34;, &#34;type&#34;: &#34;text&#34;, &#34;default&#34;: &#34;Guestbook&#34;, &#34;maxLength&#34;: 100,
      &#34;label&#34;: { &#34;th&#34;: &#34;หัวข้อหน้า&#34;, &#34;en&#34;: &#34;Page title&#34; } },
    { &#34;key&#34;: &#34;notify&#34;, &#34;type&#34;: &#34;boolean&#34;, &#34;default&#34;: true,
      &#34;label&#34;: { &#34;th&#34;: &#34;ส่งอีเมลแจ้งเมื่อมีข้อความใหม่&#34;, &#34;en&#34;: &#34;Email me on new entries&#34; } }
  ],
  &#34;code&#34;: {
    &#34;entry&#34;: &#34;code/main.ts&#34;,
    &#34;scopes&#34;: [&#34;db&#34;, &#34;routes&#34;, &#34;mail&#34;, &#34;admin-pages&#34;],
    &#34;routes&#34;: [&#34;/guestbook&#34;]
  }
}
```

Permissions asked for: `db` (its own table), `routes` (the `/guestbook` page), `mail` (notifications + reading the administrator email), `admin-pages` (the admin page).

## 3. Migration

```ts
// 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)

```ts
const esc = (s: unknown) => String(s ?? '').replace(/[&<>&#34;']/g, (c) =>
  ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '&#34;': '&quot;', &#34;'&#34;: '&#39;' } 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=&#34;gb&#34;><h1>${esc(title)}</h1>
        <form method=&#34;post&#34; action=&#34;/guestbook&#34;>
          <input name=&#34;name&#34; required maxlength=&#34;80&#34; placeholder=&#34;Name&#34;>
          <textarea name=&#34;message&#34; required maxlength=&#34;1000&#34; placeholder=&#34;Message&#34;></textarea>
          <button type=&#34;submit&#34;>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=&#34;ak-btn&#34; onclick=&#34;del(${Number(r.id)})&#34;>Delete</button></td></tr>`).join('');
    return {
      title: 'Guestbook',
      html: `<header class=&#34;ak-page-head&#34;><h1>Guestbook</h1></header>
        <div class=&#34;ak-table-wrap&#34;><table class=&#34;ak-table&#34;><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>`,
    };
  },
});
```

> [!NOTE]
> 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

1. Zip the folder: `cd guestbook && zip -r ../guestbook-1.0.0.zip .`
2. **Plugins → Upload .zip** → check the 4 permissions → **Approve and install** → **Activate** (the migration runs now)
3. Open `https://your-site/guestbook` and send a message
4. A **Guestbook** menu appears in the admin — try deleting a message
5. **Plugins → Guestbook → Settings**: change the page title, then refresh `/guestbook`
6. 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](/docs/en/developers/designer-bindings))
- Block spam with a honeypot field and count sends per IP with `request.ip`
- Let other plugins know about new messages: declare `&#34;hooks&#34;: { &#34;events&#34;: [&#34;guestbook.created&#34;] }` and call `site.emit('guestbook.created', { id })`
- Ready to share: write a Thai/English README, add images to `screenshots/` and [publish on the Plugin Store](/docs/en/store/publish-plugin)

More examples in the repository: `examples/js-plugins/` (`thai`, `promptpay`, `files`, `admin-crud`, `members`, `money` + `shop`) and the official plugins' sources in `plugins-official/`.
