O

ouhammmourachid / forms-backend

Public

Point any HTML form at /f/{slug}: submissions are stored, spam is caught by a honeypot, and you get an email for each one.

  • Automation
  • 0 deploys
  • 0 forks

Forms Backend for static sites

Point any HTML form at /f/{slug}: submissions are stored, spam is caught by a honeypot, and you get an email for each one.

What you get

  • POST /f/{slug} accepts HTML form posts, JSON and multipart
  • Email notification for every submission
  • Honeypot field (_gotcha) marks bot submissions as spam
  • Optional redirect to a thank-you page after submitting
  • Each user manages their own forms and sees only their submissions

Collections

forms

FieldTypeNotes
name (required)text
slug (required)textUsed in the URL: /f/{slug}
owner (required)relation → usersSet by a hook to the signed-in user
notify_emailemailWhere to send notifications
redirect_urlurlThank-you page (optional)
disabledboolStop accepting submissions
ActionWho can do it
List / viewowner = @request.auth.id
Createsigned-in users
Updateowner = @request.auth.id
Deleteowner = @request.auth.id

submissions

Written by the /f/{slug} route only.

FieldTypeNotes
form (required)relation → forms
datajsonThe submitted fields
iptext
user_agenttext
spamboolHoneypot was filled in
ActionWho can do it
List / viewform.owner = @request.auth.id
Createsuperusers only
Updatesuperusers only
Deleteform.owner = @request.auth.id

Hooks

All hooks are in pb_hooks/main.pb.js and commented.

Setup

  • Set SMTP in Settings for email notifications.
  • Turn on Rate limiting in Settings to slow down abuse of the public endpoint.

Quick start

<form action="https://YOUR-INSTANCE.pocketshub.com/f/contact" method="POST">
  <input name="email" type="email" required>
  <textarea name="message" required></textarea>
  <input name="_gotcha" style="display:none" tabindex="-1" autocomplete="off">
  <button>Send</button>
</form>

Notes

  • Create the form record first (in the dashboard or with the SDK), with slug contact.

License

MIT

forms
  • id
  • name
  • slug
  • ownersingle
  • notify_email
  • redirect_url
  • disabled
  • created
  • updated
submissions
  • id
  • formsingle
  • data
  • ip
  • user_agent
  • spam
  • created
  • updated

2 collections, 1 relation. Hover a collection to trace its relations

main.pb.js74 lines
/// <reference path="../pb_data/types.d.ts" />

// Forms belong to the signed-in user who creates them.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to create forms.")
    e.record.set("owner", e.auth.id)
  }
  e.next()
}, "forms")

onRecordUpdateRequest((e) => {
  if (!e.hasSuperuserAuth() && e.record.original().getString("owner") !== e.record.getString("owner")) {
    throw new ForbiddenError("A form can't be moved to another user.")
  }
  e.next()
}, "forms")

// POST /f/{slug}  - public endpoint for HTML forms and fetch().
//   <form action="https://YOUR-INSTANCE/f/contact" method="POST"> ... </form>
// Accepts JSON, urlencoded or multipart bodies. Fields starting with "_" are not stored.
// "_gotcha" is a honeypot: hide it with CSS; bots fill it in and get marked as spam.
routerAdd("POST", "/f/{slug}", (e) => {
  const esc = (s) =>
    String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")

  let form
  try {
    form = $app.findFirstRecordByData("forms", "slug", e.request.pathValue("slug"))
  } catch (_) {
    throw new NotFoundError("Form not found.")
  }
  if (form.getBool("disabled")) throw new NotFoundError("Form not found.")

  const body = e.requestInfo().body || {}
  const isSpam = !!body._gotcha
  const data = {}
  for (const key of Object.keys(body)) {
    if (key.charAt(0) !== "_") data[key] = body[key]
  }
  if (Object.keys(data).length === 0) throw new BadRequestError("The submission is empty.")

  const submission = new Record($app.findCollectionByNameOrId("submissions"))
  submission.set("form", form.id)
  submission.set("data", data)
  submission.set("ip", e.realIP())
  submission.set("user_agent", (e.request.header.get("User-Agent") || "").slice(0, 500))
  submission.set("spam", isSpam)
  $app.save(submission)

  const notify = form.getString("notify_email")
  if (notify && !isSpam) {
    try {
      const meta = $app.settings().meta
      const rows = Object.keys(data)
        .map((k) => `<tr><td><b>${esc(k)}</b></td><td>${esc(data[k])}</td></tr>`)
        .join("")
      $app.newMailClient().send(
        new MailerMessage({
          from: { address: meta.senderAddress, name: meta.senderName },
          to: [{ address: notify }],
          subject: `New submission: ${form.getString("name")}`,
          html: `<table cellpadding="6">${rows}</table>`,
        }),
      )
    } catch (err) {
      $app.logger().error("Form notification failed", "form", form.id, "error", String(err))
    }
  }

  const redirectUrl = form.getString("redirect_url")
  if (redirectUrl) return e.redirect(303, redirectUrl)
  return e.json(200, { ok: true })
})