@formforkio/node
v1.0.0
Published
Official FormFork Node.js & Server SDK with API key management, HMAC webhook verification, and Fallback Node manifest/spool sync
Maintainers
Readme
@formforkio/node
Official Node.js & Backend Server SDK for FormFork.
Built for Node.js 18+, Next.js Route Handlers, Express, Fastify, Remix, and serverless workers. Provides server-side form submission with automatic Store-and-Forward failover, V1 REST API querying (listForms, listSubmissions), constant-time HMAC-SHA256 webhook verification, and Fallback Node security orchestration (syncFallbackManifest, createFallbackTicket, drainFallbackSpool, hashTokenForManifest).
Features
- Resilient Backend Submissions (
submit): Submits withAuthorization: Bearer ff_live_...andX-FormFork-Idempotency-Keydeduplication. Automatically fails over to your Store-and-Forward Fallback Node (fallbackEndpoint) on5xxor network timeout (4500msdefault). - Offline Fallback Security Orchestration:
syncFallbackManifest: Pushes an HMAC-SHA256 signed allowlist of activeformIds, allowedOrigindomains, SHA-256 token hashes, and file size policies to your fallback server (?action=sync_manifest).createFallbackTicket: Generates stateless HMAC-SHA256 signed tickets (X-FormFork-Ticket) that prove a frontend form and domain are authorized even before a manifest sync occurs.drainFallbackSpool: Triggers?action=drainon your fallback server to replay spooled submissions back to the primary FormFork server.
- Webhook Signature Verification (
verifyWebhookSignature): Constant-timecrypto.timingSafeEqualverification ofX-FormFork-Signatureheaders.
Installation
# npm
npm install @formforkio/node
# pnpm
pnpm add @formforkio/node
# yarn
yarn add @formforkio/node
# bun
bun add @formforkio/nodeQuick Start
1. Initializing the Client & Submitting from a Backend Server
import { FormForkNodeClient } from '@formforkio/node';
const formfork = new FormForkNodeClient({
apiKey: process.env.FORMFORK_API_KEY!, // ff_live_...
endpoint: 'https://forms.yourdomain.com',
fallbackEndpoint: 'https://fallback.yourdomain.com/index.php',
fallbackSecretKey: process.env.FORMFORK_FALLBACK_SECRET,
timeoutMs: 4500,
});
const response = await formfork.submit({
formId: 'form-enterprise-demo',
origin: 'https://yourdomain.com',
ip: '203.0.113.42',
userAgent: 'Mozilla/5.0 ...',
data: {
email: '[email protected]',
seats: 250,
notes: 'Requires SSO + dedicated Postgres',
},
});
if (response.ok) {
console.log(
response.queuedOnFallback
? `Queued on fallback node (Spool ID: ${response.spoolId})`
: `Saved on primary server (Submission ID: ${response.submissionId})`
);
}2. Synchronizing Legitimate Forms & Domains to Your Fallback Server
So your fallback server (/storage-node-scripts/fallback-php/index.php) knows which formIds, website domains (Origin/Referer), and tokens (ff_pub_... / ff_live_...) are legitimate while the main server is offline, call syncFallbackManifest whenever forms are created/updated or from a scheduled job:
import { FormForkNodeClient } from '@formforkio/node';
const formfork = new FormForkNodeClient({
apiKey: process.env.FORMFORK_API_KEY!,
endpoint: 'https://forms.yourdomain.com',
fallbackEndpoint: 'https://fallback.yourdomain.com/index.php',
fallbackSecretKey: process.env.FORMFORK_FALLBACK_SECRET!,
});
const syncResult = await formfork.syncFallbackManifest({
version: 1,
updatedAt: Math.floor(Date.now() / 1000),
requireManifest: true,
forms: {
'form-contact-sales': {
active: true,
allowedDomains: ['yourdomain.com', '*.yourdomain.com'],
publicTokenHashes: [
// Fallback server stores only SHA-256 hashes, never raw tokens
FormForkNodeClient.hashTokenForManifest('ff_pub_live_98a7bc65d4e3f210'),
],
allowFiles: true,
maxFileMb: 25,
},
'form-newsletter': {
active: true,
allowedDomains: ['yourdomain.com', 'blog.yourdomain.com'],
allowFiles: false,
maxFileMb: 0,
},
},
});
console.log(`Synced ${syncResult.formsCount} forms to fallback node.`);3. Issuing Stateless Cryptographic Fallback Tickets (X-FormFork-Ticket)
For newly created forms or static sites where you want immediate cryptographic proof of legitimacy without waiting for a manifest sync, generate a signed X-FormFork-Ticket and pass it to @formforkio/js, @formforkio/vue, @formforkio/svelte, or ff-resilient.js:
const ticket = formfork.createFallbackTicket({
formId: 'form-contact-sales',
allowedDomains: ['yourdomain.com', '*.yourdomain.com'],
allowFiles: true,
maxFileMb: 15,
ttlSeconds: 86400 * 30, // Valid for 30 days
});
// Pass `ticket` to your frontend as `fallbackTicket` or `data-ff-ticket`4. Draining the Fallback Spool Back to the Primary Server
Trigger your fallback node to replay queued submissions once your primary server is back online:
const drainReport = await formfork.drainFallbackSpool(25);
console.log('Drain report:', drainReport);
// { ok: true, drained: 12, remaining: 0, failed: 0 }5. Verifying Webhooks (verifyWebhookSignature)
import express from 'express';
import { FormForkNodeClient } from '@formforkio/node';
const app = express();
const formfork = new FormForkNodeClient({ apiKey: process.env.FORMFORK_API_KEY! });
app.post(
'/webhooks/formfork',
express.raw({ type: 'application/json' }),
(req, res) => {
const signature = req.header('x-formfork-signature') || '';
const isValid = formfork.verifyWebhookSignature(
req.body,
signature,
process.env.FORMFORK_WEBHOOK_SECRET!
);
if (!isValid) {
return res.status(401).json({ error: 'Invalid webhook signature' });
}
const event = JSON.parse(req.body.toString('utf8'));
console.log('Verified webhook event:', event);
res.json({ ok: true });
}
);6. Querying Forms & Submissions via V1 API
// List all forms in the workspace
const forms = await formfork.listForms();
// Fetch the latest 100 submissions for a specific form
const submissions = await formfork.listSubmissions('form-contact-sales', 100);API Reference (FormForkNodeClient)
| Method | Signature | Description |
| :--- | :--- | :--- |
| submit | (options: SubmitFormOptions) => Promise<{ ok, queuedOnFallback, submissionId?, spoolId?, status }> | Submits a form payload to primary server with automatic failover to fallbackEndpoint. |
| listForms | () => Promise<unknown[]> | Fetches workspace forms from GET /api/v1/forms. |
| listSubmissions | (formId: string, limit?: number) => Promise<unknown[]> | Fetches submissions for a form from GET /api/v1/submissions. |
| verifyWebhookSignature | (rawBody: string \| Buffer, signatureHeader: string, webhookSecret: string) => boolean | Verifies X-FormFork-Signature using HMAC-SHA256 and crypto.timingSafeEqual. |
| createFallbackTicket | (input: FallbackTicketInput) => string | Creates a stateless HMAC-signed X-FormFork-Ticket (<base64url>.<hmacHex>). |
| syncFallbackManifest | (manifest: FallbackManifestPayload) => Promise<{ ok, formsCount, updatedAt }> | Pushes a signed allowlist manifest to ?action=sync_manifest on the fallback node. |
| drainFallbackSpool | (batchSize?: number) => Promise<Record<string, unknown>> | Triggers ?action=drain on the fallback node to replay spooled submissions. |
| FormForkNodeClient.hashTokenForManifest | (token: string) => string | Static helper that returns the lowercase SHA-256 hex digest of an ff_pub_... or ff_live_... token. |
License
MIT
