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

# FormPostbox form integration — React

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 React.

## 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 → React** 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

```tsx
'use client';

import {FormEvent,useEffect,useRef,useState} from 'react';

declare global {
  interface Window {
    turnstile?: {
      render(element: HTMLElement, options: Record<string, unknown>): string;
      reset(widgetId?: string): void;
      remove(widgetId?: string): void;
    };
    __fiTurnstileLoader?: Promise<void>;
  }
}

const endpoint = "https://formpostbox.com/f/YOUR_FORM_ID";
const siteKey = "YOUR_TURNSTILE_SITE_KEY";
const newIntent = () => crypto.randomUUID();

export function ContactForm() {
  const formElement = useRef<HTMLFormElement>(null);
  const widgetElement = useRef<HTMLDivElement>(null);
  const widgetId = useRef<string | undefined>(undefined);
  const [intentId,setIntentId] = useState('');
  const [token,setToken] = useState('');
  const [error,setError] = useState('');
  const sending = useRef(false);
  const [busy,setBusy] = useState(false);

  const resetTurnstile = () => {
    setToken('');
    if (widgetId.current !== undefined) window.turnstile?.reset(widgetId.current);
  };
  const startNewMessage = () => {
    setIntentId(newIntent());
    resetTurnstile();
    setError('');
  };

  useEffect(() => {
    let disposed = false;
    const loadTurnstile = () => {
      if (window.turnstile) return Promise.resolve();
      if (window.__fiTurnstileLoader) return window.__fiTurnstileLoader;
      window.__fiTurnstileLoader = new Promise((resolve,reject) => {
        const existing = document.querySelector<HTMLScriptElement>('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.appendChild(script);
        }
      });
      return window.__fiTurnstileLoader;
    };
    const renderTurnstile = () => {
      if (disposed || !window.turnstile || !widgetElement.current || widgetId.current !== undefined) return;
      widgetId.current = window.turnstile.render(widgetElement.current, {
        sitekey: siteKey,
        action: 'form_inbox',
        'response-field': false,
        callback: (value: string) => setToken(String(value)),
        'expired-callback': resetTurnstile,
        'error-callback': resetTurnstile,
      });
    };
    setIntentId(newIntent());
    loadTurnstile().then(renderTurnstile).catch(() => setError('Turnstile could not load. Try again.'));
    return () => {
      disposed = true;
      if (widgetId.current !== undefined) {
        window.turnstile?.remove(widgetId.current);
        widgetId.current = undefined;
      }
    };
  },[]);

  const clearFields = () => {
    formElement.current?.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 = '';
    });
  };

  async function handleSubmit(event:FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (sending.current) return;
    if (!token || !intentId) { setError('Complete the Turnstile check, then try again.'); resetTurnstile(); return; }
    const payload = Object.fromEntries(new FormData(event.currentTarget).entries());
    sending.current = true;
    setBusy(true);
    setError('Sending…');
    try {
      const result = await fetch(endpoint, {method:'POST',headers:{'Content-Type':'application/json',Accept:'application/json'},body:JSON.stringify(payload)});
      const body = await result.json().catch(() => null);
      if (result.status === 409 && body?.error === 'conflict') {
        setError('This message conflicts with an earlier submission. Restore the original content to retry, or choose New message to start again.');
        resetTurnstile();
        return;
      }
      if (!result.ok || !body?.saved) {
        setError(body?.saved === false ? 'Message was not saved. Try again.' : 'Could not confirm saving. Retry the same message.');
        resetTurnstile();
        return;
      }
      clearFields();
      startNewMessage();
      setError('Message saved.');
    } catch {
      setError('Could not confirm saving. Retry the same message.');
      resetTurnstile();
    } finally {
      sending.current = false;
      setBusy(false);
    }
  }

  function handleReset(event:FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (sending.current) return;
    clearFields();
    startNewMessage();
  }

  return (
    <form ref={formElement} action={endpoint} method="post" onSubmit={handleSubmit} onReset={handleReset}>
      <label>Email <input type="email" name="email" autoComplete="email" maxLength={254} required /></label>
      <label>Message <textarea name="message" maxLength={5000} required /></label>
      <input type="hidden" name="_intent_id" value={intentId} />
      <input type="hidden" name="cf-turnstile-response" value={token} />
      <div ref={widgetElement} data-sitekey={siteKey} data-action="form_inbox" />
      {error && <p role="alert">{error}</p>}
      <button type="submit" disabled={busy}>Send message</button>
      <button type="reset" disabled={busy}>New message</button>
    </form>
  );
}

// Keep _intent_id unchanged when retrying the same request. onReset starts a new message.
```

## Placement

Keep the 'use client' directive: the component runs in the browser and mounts Turnstile itself. Import it into your page and render it where the form should appear. No server component or route handler is required.

## 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/react/SKILL.md (this file) · https://formpostbox.com/skills/react/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
