---
name: formpostbox-astro
description: Connect an existing Astro website form to FormPostbox: required fields, intent retry rules, Turnstile lifecycle, status handling and a reference implementation.
---

# FormPostbox form integration — Astro

FormPostbox gives a website an inbox for its forms: an existing form posts to a per-form endpoint, FormPostbox stores each submission and tracks its email notification separately. This skill describes the browser integration contract and a reference implementation for Astro.

## Before you start

- This page's code is a protected-site example. Protection is optional per site. For an unprotected site, copy the generated code from **Connect your website → Astro** on the form page; that version omits the widget, Turnstile script, response field and token check.
- The real values come from the customer's FormPostbox form page: **Connect your website → Use AI to connect** generates a prompt with the actual `submissionEndpoint`, `allowedOrigins` and, when protection is enabled, `turnstileSiteKey`.
- The placeholders below (`YOUR_FORM_ID`, `YOUR_TURNSTILE_SITE_KEY`) are not usable values. Replace them with the customer's real values — never guess them.

## Integration rules

- Use `fetch` to POST to the form's submission endpoint (`https://formpostbox.com/f/{form-id}`), with `Accept: application/json` and a body encoded as `application/json` or `application/x-www-form-urlencoded`; never use `multipart`. The reference implementation uses this JSON response to confirm `saved: true`.
- On a protected site, send the Turnstile token in `cf-turnstile-response`; an unprotected site needs no widget or token. If this field is supplied on an unprotected site, a response up to 2048 characters is ignored; longer responses exceed the request limit. Always send the request intent in `_intent_id` (16–128 characters; `crypto.randomUUID()` works).
- Create `_intent_id` once per message; after a network error or unknown result, retry the same content with the same intent. Changed content with that intent gets `409 conflict`; restoring the original content can replay it only while the submission is retained. For a genuinely new message, create a new intent only after the user explicitly starts it.
- A disallowed origin may appear as a browser CORS or network error because the response can be hidden. Check the page's scheme, hostname and port against the allowed origins; the FormPostbox form page shows the rejected origin. After correcting it, retry with the same intent.
- Never hardcode a Turnstile token. Clear it when the challenge expires or fails and render a fresh challenge.
- Load `https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit` once per page; reuse it if the page already has it.
- Handle submitting, each failure, success (reset for a new message) and an explicit new-message action; apply the retry rules above.
- A submission is saved only when the JSON response contains `saved: true`; HTTP 200/201 alone is not proof. A retry of the same intent and content returns `replayed: true` with the original record ID.
- `429 quota` means the monthly allowance is exhausted; `429 rate_limit` means the request rate was exceeded and can be retried later.
- `notification: "queued"` only means the email side is queued; it never confirms delivery. `notification: "off"` means email notifications were disabled; the submission is still saved.
- Keep the existing layout, styles, fields and validation, and keep every field's `name`.
- Limits: business field names are 1–128 characters; at most 50 business fields (excluding `_intent_id` and `cf-turnstile-response` in all cases); values at most 32768 characters; JSON and URL-encoded request bodies at most 65536 bytes; normalized business-fields JSON at most 65536 bytes; a supplied `cf-turnstile-response` is at most 2048 characters. Attachments and non-string values are unsupported.
- Browser integration uses public values only: no FormPostbox API key and no server-side proxy.

## Reference implementation

```astro
---
const formAction = "https://formpostbox.com/f/YOUR_FORM_ID";
const turnstileSiteKey = "YOUR_TURNSTILE_SITE_KEY";
---

<form data-fi-form action={formAction} method="post">
  <label>
    Email
    <input type="email" name="email" autocomplete="email" maxlength="254" required />
  </label>
  <label>
    Message
    <textarea name="message" maxlength="5000" required></textarea>
  </label>
  <input type="hidden" name="_intent_id" value="" />
  <input type="hidden" name="cf-turnstile-response" value="" />
  <div data-fi-turnstile data-sitekey={turnstileSiteKey} data-action="form_inbox"></div>
  <button type="submit">Send message</button>
  <button type="reset">New message</button>
</form>
<script is:inline>
(() => {
  const form = document.currentScript?.previousElementSibling;
  if (!(form instanceof HTMLFormElement)) return;
  const intent = form.elements.namedItem("_intent_id");
  const response = form.elements.namedItem("cf-turnstile-response");
  const container = form.querySelector("[data-fi-turnstile]");
  if (!(intent instanceof HTMLInputElement) || !(response instanceof HTMLInputElement) || !(container instanceof HTMLElement)) return;
  let widgetId;
  let sending = false;
  const status = document.createElement("p");
  status.setAttribute("role", "status");
  form.append(status);
  const resetTurnstile = () => {
    response.value = "";
    if (widgetId !== undefined && window.turnstile) window.turnstile.reset(widgetId);
  };
  const clearFields = () => {
    form.querySelectorAll("input:not([type=hidden]), textarea, select").forEach((field) => {
      if (field instanceof HTMLInputElement && ["button", "submit", "reset", "image"].includes(field.type)) return;
      if (field instanceof HTMLInputElement && (field.type === "checkbox" || field.type === "radio")) field.checked = false;
      else if (field instanceof HTMLSelectElement) field.selectedIndex = -1;
      else if (field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement) field.value = "";
    });
  };
  const startNewMessage = () => {
    intent.value = crypto.randomUUID();
    resetTurnstile();
  };
  const tokenReceived = (token) => { response.value = token; };
  const challengeFailed = () => { resetTurnstile(); };
  const renderTurnstile = () => {
    if (!window.turnstile || widgetId !== undefined) return;
    widgetId = window.turnstile.render(container, {
      sitekey: "YOUR_TURNSTILE_SITE_KEY",
      action: "form_inbox",
      "response-field": false,
      callback: tokenReceived,
      "expired-callback": challengeFailed,
      "error-callback": challengeFailed
    });
  };
  const loadTurnstile = () => {
    if (window.turnstile) return Promise.resolve();
    const sharedKey = "__fiTurnstileLoader";
    if (window[sharedKey]) return window[sharedKey];
    window[sharedKey] = new Promise((resolve, reject) => {
      const existing = document.querySelector('script[data-fi-turnstile-script], script[src^="https://challenges.cloudflare.com/turnstile/v0/api.js"]');
      const script = existing || document.createElement("script");
      script.addEventListener("load", () => resolve(), {once: true});
      script.addEventListener("error", reject, {once: true});
      if (!existing) {
        script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
        script.async = true;
        script.defer = true;
        script.setAttribute("data-fi-turnstile-script", "");
        document.head.append(script);
      }
    });
    return window[sharedKey];
  };
  form.addEventListener("reset", (event) => {
    // Prevent the native reset from clearing the newly generated intent.
    event.preventDefault();
    if (sending) return;
    clearFields();
    startNewMessage();
    status.textContent = "";
  });
  form.addEventListener("submit", async (event) => {
    event.preventDefault();
    if (sending) return;
    // A network retry reuses this intent; only a new message rotates it.
    if (!response.value) { status.textContent = "Complete the Turnstile check, then try again."; challengeFailed(); return; }
    sending = true;
    form.querySelectorAll("button").forEach((button) => { button.disabled = true; });
    status.textContent = "Sending…";
    try {
      const payload = Object.fromEntries(new FormData(form).entries());
      const result = await fetch(form.action, {method: "POST", body: JSON.stringify(payload), headers: {"Content-Type": "application/json", Accept: "application/json"}});
      const body = await result.json().catch(() => null);
      if (result.status === 409 && body?.error === "conflict") {
        status.textContent = "This message conflicts with an earlier submission. Restore the original content to retry, or choose New message to start again.";
        challengeFailed();
        return;
      }
      if (body?.saved === false) {
        status.textContent = "Message was not saved. Try again.";
        challengeFailed();
        return;
      }
      if (!result.ok || !body?.saved) {
        status.textContent = "Could not confirm saving. Retry the same message.";
        challengeFailed();
        return;
      }
      status.textContent = "Message saved.";
      clearFields();
      startNewMessage();
    } catch {
      status.textContent = "Could not confirm saving. Retry the same message.";
      challengeFailed();
    } finally {
      sending = false;
      form.querySelectorAll("button").forEach((button) => { button.disabled = false; });
    }
  });
  startNewMessage();
loadTurnstile().then(renderTurnstile).catch(challengeFailed);
})();
</script>
```

## Placement

Keep the frontmatter constants and the `is:inline` script: Astro ships the markup as-is and the script runs the same form lifecycle in the browser.

## Verify

- Build or type-check the host project if it has such a step.
- Submit a test message and confirm the endpoint answered `saved: true`.
- Simulate a network failure, retry, and confirm the message is stored exactly once.
- Submit a second message after a success and confirm it saves too.

## More

- Skill files: https://formpostbox.com/skills/astro/SKILL.md (this file) · https://formpostbox.com/skills/astro/SKILL.zh-CN.md (Simplified Chinese)
- AI integration guide: https://formpostbox.com/docs/ai-integration
- Submission contract (Markdown): https://formpostbox.com/skills/integration-guide.md
- Index for AI tools: https://formpostbox.com/llms.txt
