Put a form on a site
A published page posts to a *.api.sh on the same mount. The handler reads the request, writes data, then redirects. There is no separate backend process.
This is not a platform webhook. A webhook starts a background goal. A form handler is short bash that must finish in one request.
Done looks like
The visitor submits. The browser lands on a thanks page (HTTP 303). A row exists in sql --db, or a file exists under the site. handler-test against the script returns status 303 without hitting the live URL.
Worked example: public newsletter subscribe
Job: anonymous visitors on a public site (--policy 644) can POST an email. You store one row per address. A second submit with the same email is a no-op.
Every command and output below was run against a throwaway public mount.
Start from a site folder that already publishes (copy a template if you need one):
cp -r /templates/static-site-demo ./site
1. The form page
site/pages/newsletter/index.page.md:
---
title: Newsletter
excerpt: Subscribe.
draft: false
---
<form method="post" action="/newsletter/subscribe">
<label>
Email
<input type="email" name="email" required>
</label>
<button type="submit">Subscribe</button>
</form>
action is a site path, not a full URL. The file pages/newsletter/subscribe.api.sh handles POST /newsletter/subscribe.
The thanks page site/pages/newsletter/thanks.page.md can be a short "you're in" note. The handler will respond redirect /newsletter/thanks.
2. The table
App rows go in a .db bundle with sql --db, not a page glob and not sails.data.json. New bundles are sqlite by default. Rows live in a per-branch sidecar, not in a workspace file, and the cap is 64 MiB. Attach Postgres with createdb --url only when you outgrow that.
createdb site/app.db
# Created database `/ryan/home/site/app.db` (sqlite)
sql --db site/app.db --exec "
CREATE TABLE IF NOT EXISTS subscribers (
email_lower text PRIMARY KEY,
email text NOT NULL,
created_at text NOT NULL DEFAULT (datetime('now'))
)
"
# { "affected": 0 }
Write sqlite DDL. Postgres syntax such as timestamptz DEFAULT now() fails on the default engine with near "(": syntax error. datetime('now') stores UTC text like 2026-10-22 15:16:39. email_lower is the unique key.
See Keep app data in a database.
3. The handler
site/pages/newsletter/subscribe.api.sh:
---
methods: [POST]
security: definer
redirect: /newsletter/thanks
body:
type: object
required: [email]
properties:
email: { type: string, minLength: 3 }
---
#!/usr/bin/env bash
set -euo pipefail
email="$(request param email)"
email_lower="$(printf '%s' "$email" | tr '[:upper:]' '[:lower:]')"
sql --db app.db --exec \
"INSERT INTO subscribers (email_lower, email) VALUES (?, ?) ON CONFLICT (email_lower) DO NOTHING" \
"$email_lower" "$email"
respond redirect /newsletter/thanks
--db app.db inside a handler is relative to the published mount root (site/ if you published --path site). Both handler-test and the live mount wrote to site/app.db in testing. Keep the bundle next to sails.site.json.
security: definer runs as the publisher, so anonymous visitors can write. Keep the script narrow. Only repository owners may create or edit *.api.sh files that declare security: definer. check prints a warning on every definer handler; that is expected.
If the visitor is signed in and should write as themselves, omit security: (default invoker) and set auth: required.
Invalid body: never reaches the script (400). Trust required / minLength / format for those fields. Still bind SQL with ?. Never eval the email.
If you later run sql owner enable on this table, ON CONFLICT DO NOTHING stops working for invoker writes (cannot UPSERT a view). Use INSERT OR IGNORE there instead. See SQL.
4. Dry-run, then publish
check --path site
handler-test site/pages/newsletter/subscribe.api.sh \
--method POST --form 'email=Ada@Example.com'
check prints a JSON report; look for "ok": true. check --path is relative to your current directory, while ship create --path is relative to the repository root. If you are not at the root, check warns that it resolved the path from cwd. Use the root-relative path for ship create.
handler-test prints the response it would send:
{
"kind": "api",
"status": 303,
"headers": [["Location", "/newsletter/thanks"]],
"body": "",
"exit_code": 0,
"stderr": ""
}
It runs against the session workspace, not the live URL, and the row it inserts is real. A form without email returns 400 with {"details":["\"email\" is a required property"],"error":"validation failed"}. --method GET returns 405 method not allowed. --auth only toggles signed_in; you cannot forge sub. A definer dry-run still uses your identity; it does not become the publisher.
ship create newsletter --path site --policy 644
--policy 644 is public. Default 600 is owner-only, so strangers cannot POST. Publish once; autosave redeploys. The JSON output includes public_url, which is https://{org}-{name}.sails.app/ unless you pass --hostname. See Publish a site.
Then POST for real:
curl -s -D - -o /dev/null \
-X POST "https://{org}-newsletter.sails.app/newsletter/subscribe" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'email=grace@example.com'
Expect HTTP/2 303, location: /newsletter/thanks (same mount), and cache-control: no-store, no-transform (any sql --db makes the response uncacheable). Confirm the row from the workspace:
sql --db site/app.db "SELECT email, email_lower FROM subscribers WHERE email_lower = ?" "grace@example.com"
Shape: { "columns": ["email", "email_lower"], "rows": [{ "email": "grace@example.com", "email_lower": "grace@example.com" }] }. The live POST persists sqlite before HTTP 200; workspace sql sees that committed row without sql reload.
Take a file with the form
A plain HTML file input does not work on a published handler. Tested on a throwaway public mount on 2026-11-05:
| What the browser sends | What happens live |
|---|---|
<form enctype="multipart/form-data"> with <input type="file"> (or curl -F) | HTTP 500 multipart file uploads are not supported in published api scripts. The script never runs, even with no file field. |
Raw binary body (Content-Type: application/octet-stream) | Accepted, but not byte safe. A 3000 byte random file was stored as 5442 bytes. |
Text body (JSON, form-urlencoded, text/plain) | Arrives exactly. |
| Any body over 1 MiB (1,048,576 bytes) | HTTP 413 Failed to buffer the request body: length limit exceeded. |
handler-test does not catch the first row. A multipart dry run returns your script's normal status, with request form and request param empty. Test uploads against a live mount with curl, not only with handler-test.
The pattern that works: the page reads the file in the browser, sends it as base64 inside a JSON body, and the handler decodes it. Base64 makes the body about 4/3 the file size, so the file limit is about 750 KB. For bigger files, see the last part of this section.
The page
<form id="apply">
<label>Email <input type="email" name="email" required></label>
<label>Resume (PDF, max 700 KB) <input type="file" name="resume" accept="application/pdf" required></label>
<button type="submit">Apply</button>
<p id="apply-status"></p>
</form>
<script>
document.getElementById("apply").addEventListener("submit", async (e) => {
e.preventDefault();
const form = e.target;
const status = document.getElementById("apply-status");
const file = form.resume.files[0];
if (file.size > 700 * 1024) { status.textContent = "File is too large."; return; }
const dataUrl = await new Promise((ok, fail) => {
const r = new FileReader();
r.onload = () => ok(r.result);
r.onerror = fail;
r.readAsDataURL(file);
});
const res = await fetch("/apply/submit", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: form.email.value,
file_name: file.name,
file_b64: dataUrl.split(",")[1]
})
});
status.textContent = res.ok ? "Thanks, we got it." : "Upload failed (" + res.status + ").";
});
</script>
readAsDataURL returns data:application/pdf;base64,..... The part after the comma is the base64 with no line breaks. Check the size in the browser too, so a large file gets a clear message instead of a bare 413.
The handler
pages/apply/submit.api.sh:
---
methods: [POST]
security: definer
body:
type: object
required: [email, file_name, file_b64]
properties:
email: { type: string, format: email }
file_name: { type: string, minLength: 1, maxLength: 120 }
file_b64: { type: string, minLength: 4, maxLength: 1000000 }
---
#!/usr/bin/env bash
set -euo pipefail
prefix="${SAILS_SITE_ROOT:+$SAILS_SITE_ROOT/}"
id="$(uuid)"
name="$(slugify --id "$(request json file_name)")"
dir="${prefix}data/uploads/${id}"
mkdir -p "$dir"
request json file_b64 | base64 -d > "$dir/$name"
bytes="$(wc -c < "$dir/$name")"
respond 200 text/plain "$id $bytes"
This exact handler was posted to with curl --data-binary @payload.json. The stored file had the same SHA-256 and byte count as the original. Notes from that run:
slugify --iddrops dots.Resume Final.pdfwas saved asResumeFinalpdf. Keep the original name in your table row and add the extension yourself if you need one.- The
uuidfolder keeps two people who uploadresume.pdfapart. Put the same id in the applicant'ssql --dbrow so the file stays with the person. - Sails
base64 -drejects line breaks (decode failed: Invalid symbol 10).FileReaderoutput has none. If a client sends wrapped base64, decode withtr -d '\n' | base64 -d. respond 200 application/json "..."with a hand-built string fails at save time (body is String, expected Json). Reply withtext/plain, or build the reply withjson.- The 1 MiB cap is on the whole request, so the email and other fields count too.
- Keep uploads out of
pages/andpublic/, which the site builds and serves. Show them to reviewers only on a private page.
Files over about 750 KB
There is no anonymous upload path above the 1 MiB request cap. upload PATH and upload PATH --curl take up to 100 MiB, but minting either link needs a repository member session, and the browser link also needs a signed-in member. Use them for files you or a teammate add, not for strangers. See Send a file.
Flags and builtins you actually use
check help
handler-test help
sql help
| Piece | What it does |
|---|---|
methods: [POST] | Default is POST-only. Add GET only if the handler should run on navigation. |
body: / query: | JSON Schema. Invalid requests never enter the script. |
security: definer | VFS and sql --db run as the publisher. Public anonymous writes. |
auth: required | Visitor must be signed in. Does not elevate VFS by itself. |
request param FIELD | Form, then JSON, then query (first non-empty). Prefer this for HTML forms. |
request json | Parsed JSON body (typed). Use for API clients, not application/x-www-form-urlencoded. |
respond redirect /path | Primary success. Default 303. Same-mount paths only. |
SAILS_SITE_ROOT | Repo prefix of this mount (site when --path site; empty at repo root). Prefix file writes: ${SAILS_SITE_ROOT:+$SAILS_SITE_ROOT/}. |
check --path site | Front matter, MiniJinja, and handler types. Path is cwd-relative. JSON report; look at "ok". |
handler-test FILE --method POST --form 'k=v' | Dry-run against the workspace. Also --json '{...}', --query, --header, --auth '{"signed_in":true}'. |
handler-test --suite FILE.test.sh | Repeatable tests with run_api, expect_status, expect_header, expect_json. |
Do not use page sql: or sails.data.json for subscribers. Collections list pages at compile time. See Collections.
Failure modes
| What you see | What it means | What to do |
|---|---|---|
| POST 404 | No *.api.sh for that path, or it is not on this mount | File is pages/newsletter/subscribe.api.sh for /newsletter/subscribe. Publish --path must include it. |
405 method not allowed | Method not in methods | Default is POST. HTML forms are POST. |
400 validation failed before your script | body: / query: rejected the payload | Fix the form name= to match schema properties. |
near "(": syntax error on CREATE TABLE | Postgres DDL on a sqlite bundle | Use sqlite types and defaults, e.g. DEFAULT (datetime('now')). |
Live POST returns 303 but workspace sql shows no new row | Wrong --db path, or the handler did not insert | Query the same bundle the handler uses (site/app.db). |
| Write denied / empty table on a 644 site | Default invoker as anonymous "other" | Public writes need security: definer (owner-only to author). |
| Cannot save the handler | Collaborator tried to set security: definer | An owner writes that file. |
sql without --db | Flag is required | sql --db app.db ... with the bundle next to the site root. |
UNIQUE constraint failed on second submit | You used plain INSERT | ON CONFLICT (email_lower) DO NOTHING, or INSERT OR IGNORE on an owner-scoped table. |
cannot UPSERT a view | Table is owner-scoped (sql owner enable) | INSERT OR IGNORE. |
check warns the path was resolved from the current directory | check --path is cwd-relative, ship create --path is root-relative | Pass the root-relative path to ship create. |
handler-test 200 + HTML | You hit a page, not the handler | Path must end in .api.sh. |
respond redirect to another host | Same-mount only | respond redirect-external https://... if you truly need off-site. |
| Form works for you, 403 for strangers | Mount policy 600 / 640 | ship create ... --policy 644 for a public form. |
You INSERTed into a glob | Collections are not a database | sql --db. |
500 multipart file uploads are not supported in published api scripts | Form has enctype="multipart/form-data" or a file input posted directly | Read the file in the browser and POST base64 in JSON. See Take a file with the form. |
413 Failed to buffer the request body: length limit exceeded | Whole request is over 1 MiB | Keep files under about 750 KB, check size in the browser. |
| Stored file is bigger than the original and will not open | Binary sent as a raw body | Send base64 text and base64 -d in the handler. |
decode failed: Invalid symbol 10 | Base64 has line breaks | tr -d '\n' | base64 -d. |
Upload passes handler-test but fails live | handler-test does not reject multipart | Test uploads with curl against a live mount. |
See Static sites for pages vs handlers, and Mail from an agent if the handler should notify someone.