@formforkio/react
v1.0.0
Published
Official React & Next.js SDK for FormFork — Headless form hooks, Next.js Server Action helpers, webhook verification, and built-in Store-and-Forward failover.
Maintainers
Readme
@formforkio/react
Official React 18/19 & Next.js (App Router & Pages Router) SDK for FormFork.
Built with Triple-Layer Store-and-Forward Resilience, automatic anti-bot timing proof (_ff_t), zero-setup form auto-provisioning (ff_pub_...), Next.js Server Actions (@formforkio/react/server), and auto-resizing hosted embeds (@formforkio/react/embed).
Features
- Triple-Layer Failover Architecture:
- Tier 1 (Primary Server): Submits directly to your FormFork instance (
/f/{formId}or/api/v1/submit) with anAbortControllertimeout (6000msdefault). - Tier 2 (Store-and-Forward Fallback Node): Automatically fails over to your PHP/Edge Fallback Spooler (
fallbackEndpoint) on502/503/504or network timeout. - Tier 3 (Browser Offline Outbox): Persists submissions to
localStorage(formfork_offline_outbox_v1) if the user loses internet connectivity completely, and replays them automatically on thewindow.onlineevent.
- Tier 1 (Primary Server): Submits directly to your FormFork instance (
- Next.js App Router Ready: Subpath exports for Client Components (
@formforkio/react), Server Actions & Webhook Verification (@formforkio/react/server), and Hosted Iframes (@formforkio/react/embed). - Built-in Bot Protection: Automatically injects mount-timestamp proof (
_ff_t) and provides<HoneypotField />(_gotcha) with zero layout shift. - Full Multipart & File Upload Support: Accepts
<form>events (FormData),FormDatainstances, or plain JSON objects.
Installation
# npm
npm install @formforkio/react
# pnpm
pnpm add @formforkio/react
# yarn
yarn add @formforkio/react
# bun
bun add @formforkio/reactPackage Entrypoints
| Import Path | Environment | Exports |
| :--- | :--- | :--- |
| @formforkio/react | Client ('use client') | useFormFork, FormForkProvider, useFormForkContext, ValidationError, HoneypotField |
| @formforkio/react/server | Server (Next.js Server Actions / API Routes) | submitToFormFork, verifyWebhookSignature |
| @formforkio/react/embed | Client ('use client') | FormForkEmbed |
1. Client Component Usage (useFormFork)
'use client';
import { useFormFork, ValidationError, HoneypotField } from '@formforkio/react';
export function ContactForm() {
const [state, handleSubmit, reset] = useFormFork('form-contact-sales', {
endpointHost: 'https://forms.yourdomain.com',
fallbackEndpoint: 'https://fallback.yourdomain.com/index.php?formId=form-contact-sales',
timeoutMs: 5000,
extraData: {
sourcePage: '/pricing',
planInterest: 'enterprise',
},
onSuccess: (result) => {
console.log('Submitted:', result.submissionId, result.queuedViaFallback);
},
onError: (err) => {
console.warn('FormFork error:', err.code, err.message);
},
});
if (state.succeeded) {
return (
<div className="rounded-xl border border-emerald-200 bg-emerald-50 p-6">
<h3 className="text-lg font-semibold text-emerald-900">Thank you!</h3>
<p className="mt-1 text-sm text-emerald-700">
{state.queuedViaFallback
? 'Your message was securely queued by our backup node and will be processed shortly.'
: state.queuedOffline
? 'You appear to be offline. Your message is saved and will send automatically once reconnected.'
: state.result?.message || 'We received your message and will reply shortly.'}
</p>
<button
type="button"
onClick={reset}
className="mt-4 text-sm font-medium text-emerald-800 underline"
>
Send another message
</button>
</div>
);
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<HoneypotField />
<div>
<label htmlFor="email" className="block text-sm font-medium">
Work Email
</label>
<input
id="email"
name="email"
type="email"
required
className="mt-1 w-full rounded-md border px-3 py-2"
/>
<ValidationError prefix="Email" field="email" errors={state.errors} className="mt-1 text-xs text-red-600" />
</div>
<div>
<label htmlFor="message" className="block text-sm font-medium">
Message
</label>
<textarea
id="message"
name="message"
rows={4}
required
className="mt-1 w-full rounded-md border px-3 py-2"
/>
<ValidationError prefix="Message" field="message" errors={state.errors} className="mt-1 text-xs text-red-600" />
</div>
<div>
<label htmlFor="attachment" className="block text-sm font-medium">
RFP / Spec PDF (Optional)
</label>
<input id="attachment" name="attachment" type="file" accept=".pdf,.png,.jpg" />
</div>
<ValidationError errors={state.errors} className="text-sm text-red-600" />
<button
type="submit"
disabled={state.submitting}
className="rounded-lg bg-slate-900 px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
>
{state.submitting ? 'Sending...' : 'Send Message'}
</button>
</form>
);
}2. Global Workspace Provider (<FormForkProvider>)
Wrap your application layout in <FormForkProvider> to configure endpointHost, fallbackEndpoint, and embedToken once across all forms, and to enable automatic background flushing of offline localStorage submissions whenever the browser comes back online:
// app/providers.tsx
'use client';
import { FormForkProvider } from '@formforkio/react';
export function Providers({ children }: { children: React.ReactNode }) {
return (
<FormForkProvider
endpointHost="https://forms.yourdomain.com"
fallbackEndpoint="https://fallback.yourdomain.com/index.php"
embedToken="ff_pub_live_98a7bc65d4e3f210"
timeoutMs={6000}
enableOfflineOutbox={true}
>
{children}
</FormForkProvider>
);
}When embedToken (ff_pub_...) is set, you can pass any human-readable form name (e.g. useFormFork('Newsletter Footer')) and FormFork will automatically provision the form on first submission if it does not already exist.
3. Next.js Server Actions & Webhooks (@formforkio/react/server)
Keep your ff_live_... secret API keys strictly on the server using Next.js Server Actions:
// app/actions/submit-lead.ts
'use server';
import { submitToFormFork } from '@formforkio/react/server';
export async function submitEnterpriseLead(formData: FormData) {
const email = String(formData.get('email') || '');
const company = String(formData.get('company') || '');
return await submitToFormFork({
apiKey: process.env.FORMFORK_API_KEY!, // ff_live_...
formIdOrName: 'form-enterprise-leads',
siteDomain: 'yourdomain.com',
endpointHost: process.env.FORMFORK_HOST,
fallbackEndpoint: process.env.FORMFORK_FALLBACK_URL,
data: {
email,
company,
submittedFrom: 'nextjs-server-action',
},
});
}Verifying Incoming Webhooks in Next.js Route Handlers
// app/api/webhooks/formfork/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { verifyWebhookSignature } from '@formforkio/react/server';
export async function POST(req: NextRequest) {
const rawBody = await req.text();
const signature = req.headers.get('x-formfork-signature');
const isValid = verifyWebhookSignature(
rawBody,
signature,
process.env.FORMFORK_WEBHOOK_SECRET!
);
if (!isValid) {
return NextResponse.json({ error: 'Invalid HMAC signature' }, { status: 401 });
}
const event = JSON.parse(rawBody);
console.log('Verified FormFork submission:', event.submissionId);
return NextResponse.json({ received: true });
}4. Hosted Auto-Resizing Embed (@formforkio/react/embed)
Render any FormFork Drag & Drop Builder form inside an auto-resizing iframe that listens to formfork:resize postMessage events:
import { FormForkEmbed } from '@formforkio/react/embed';
export default function FeedbackSection() {
return (
<FormForkEmbed
formId="form-customer-nps"
endpointHost="https://forms.yourdomain.com"
initialHeight={480}
className="rounded-2xl shadow-sm"
title="Customer Feedback Survey"
/>
);
}API Reference
useFormFork(formIdOrFormName, options?)
Returns [state, handleSubmit, reset].
FormForkOptions
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| embedToken | string | undefined | Public embed token (ff_pub_live_... or ff_pub_dev_...) for domain-verified auto-provisioning. |
| endpointHost | string | 'https://formfork.io' | Primary FormFork instance base URL. |
| fallbackEndpoint | string | 'https://fallback.formfork.io/index.php' | Store-and-Forward fallback receiver URL used when primary returns 5xx or times out. |
| timeoutMs | number | 6000 | Primary request timeout in milliseconds before failing over to fallbackEndpoint. |
| enableOfflineOutbox | boolean | true | Save submissions to localStorage when both primary and fallback servers are unreachable. |
| extraData | Record<string, string \| number \| boolean> | undefined | Extra metadata fields merged into every submission. |
| onSuccess | (result: FormForkResult) => void | undefined | Callback fired when a submission succeeds (live, via fallback node, or offline outbox). |
| onError | (error: FormForkError) => void | undefined | Callback fired when validation fails or all tiers are unreachable. |
FormForkState
| Property | Type | Description |
| :--- | :--- | :--- |
| submitting | boolean | true while an active submission request is in flight. |
| succeeded | boolean | true once accepted by the primary server, fallback node, or offline outbox. |
| queuedViaFallback | boolean | true if the primary server was down and the Store-and-Forward fallback node spooled the submission. |
| queuedOffline | boolean | true if saved to localStorage to be sent when the browser reconnects. |
| errors | FormForkError[] | Array of field or form validation errors ({ field?, code, message }). |
| result | FormForkResult \| null | Latest submission response metadata (submissionId, message, redirectUrl). |
License
MIT
