@businessflow/leads
v2.6.0
Published
Marketing website lead collection and form submission utilities with server-side API route handlers for BusinessFlow CRM
Maintainers
Readme
@businessflow/leads
Marketing website lead collection and form submission utilities for React and NextJS applications that integrate with BusinessFlow CRM.
Features
- 🚀 Framework Agnostic: Works with React, NextJS, and vanilla JavaScript
- 🔒 Secure: Server-side API key handling, Cloudflare Turnstile (v2.6+) or reCAPTCHA verification
- 📱 Responsive: Mobile-friendly form components
- 🎨 Customizable: Flexible styling and field configuration
- 📝 TypeScript: Full type safety and IntelliSense support
- ⚡ Modern: Built with latest React patterns and NextJS features
- 🏢 BusinessFlow Ready: Pre-configured for BusinessFlow CRM integration
Installation
npm install @businessflow/leadsQuick Start
1. Simple BusinessFlow Integration
// app/api/lead/route.ts
import { createBusinessFlowHandler } from '@businessflow/leads/server';
export const POST = createBusinessFlowHandler({
apiUrl: process.env.BUSINESS_FLOW_API_URL!,
apiKey: process.env.BUSINESS_FLOW_API_KEY!,
sourceUrl: process.env.SITE_URL!,
// One of these is required in production (Turnstile wins if both are set):
turnstileSecret: process.env.TURNSTILE_SECRET_KEY,
// recaptchaSecret: process.env.RECAPTCHA_SECRET_KEY,
});2. Even Simpler with Environment Variables
// app/api/lead/route.ts
import { createSimpleBusinessFlowHandler } from '@businessflow/leads/server';
// Uses BUSINESS_FLOW_API_URL, BUSINESS_FLOW_API_KEY, and TURNSTILE_SECRET_KEY or RECAPTCHA_SECRET_KEY from env
export const POST = createSimpleBusinessFlowHandler();3. Custom Integration (Advanced)
// app/api/lead/route.ts
import { createLeadHandler } from '@businessflow/leads/server';
export const POST = createLeadHandler({
onSubmit: async (data) => {
// Your custom business logic here
const response = await fetch('https://your-api.com/leads', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.YOUR_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
return {
success: response.ok,
message: response.ok ? 'Lead submitted successfully' : 'Submission failed',
id: response.ok ? await response.json().then(r => r.id) : undefined
};
},
recaptcha: {
secretKey: process.env.RECAPTCHA_SECRET_KEY!
}
});2. Use in Your Components
Pre-built Component
import { ContactForm } from '@businessflow/leads/react';
export default function ContactPage() {
return (
<ContactForm
recaptcha={{ siteKey: process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY! }}
onSuccess={(response) => console.log('Success!', response)}
onError={(error) => console.error('Error:', error)}
/>
);
}Custom Hook for Custom Forms
import { useContactForm } from '@businessflow/leads/react';
export default function CustomContactForm() {
const {
formData,
errors,
state,
handleChange,
handleSubmit,
handleRetry,
resetForm
} = useContactForm({
endpoint: '/api/lead',
recaptcha: {
siteKey: process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY!,
action: 'contact_form'
},
onSuccess: (response) => console.log('Success!', response),
onError: (error) => console.error('Error:', error),
maxRetries: 3
});
return (
<form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>
<input
type="text"
placeholder="First Name"
value={formData.firstName}
onChange={(e) => handleChange('firstName', e.target.value)}
/>
{errors.firstName && <span>{errors.firstName}</span>}
<input
type="text"
placeholder="Last Name"
value={formData.lastName}
onChange={(e) => handleChange('lastName', e.target.value)}
/>
{errors.lastName && <span>{errors.lastName}</span>}
<input
type="email"
placeholder="Email"
value={formData.email}
onChange={(e) => handleChange('email', e.target.value)}
/>
{errors.email && <span>{errors.email}</span>}
<button type="submit" disabled={state.isSubmitting}>
{state.isSubmitting ? 'Submitting...' : 'Submit'}
</button>
{state.error && state.canRetry && (
<button onClick={handleRetry} disabled={state.isSubmitting}>
Retry ({state.retryCount}/{3})
</button>
)}
{state.isSuccess && <div>Form submitted successfully!</div>}
{state.error && <div>Error: {state.error}</div>}
</form>
);
}Bot protection
The route handler always applies a honeypot check (_website / _honeypot), and applies a
timing check when the client sends _t (page-load timestamp; submissions under 3 s are
dropped). On top of that, configure one captcha verifier. In production
(NODE_ENV=production) the BusinessFlow handlers (createBusinessFlowHandler /
createSimpleBusinessFlowHandler) refuse to start with neither, unless you pass
allowMissingCaptcha: true deliberately. The generic createLeadHandler applies no such
rule — it runs whatever verifier block you give it, or none.
| | Cloudflare Turnstile (v2.6+, recommended) | Google reCAPTCHA v3 |
|---|---|---|
| Wrapper option | turnstileSecret | recaptchaSecret, minimumScore |
| Env var (simple handler) | TURNSTILE_SECRET_KEY | RECAPTCHA_SECRET_KEY |
| Body field the route reads | token (or Token) | token (or Token) |
| Failure response | 400 Security verification failed: … | 400 reCAPTCHA verification failed: … |
| Client helper in this package | none — render the widget yourself (below) | useRecaptcha hook |
If both secrets are set (typical for one deploy while migrating), Turnstile wins and the
handler logs one warning at startup. Remove RECAPTCHA_SECRET_KEY once Turnstile is verified.
The captcha secret is only ever read inside your API route. The browser posts a one-time
token to your own /api/lead; the route verifies it with Cloudflare or Google, strips it,
and only then forwards the lead to BusinessFlow. BusinessFlow never sees captcha configuration.
Turnstile keys per environment
Turnstile's trust boundary is the widget's hostname allow-list in the Cloudflare dashboard —
the package does not check hostname/action itself, so there is nothing to configure per
environment in code.
| Environment | Site key | Secret key |
|---|---|---|
| Production | the widget you created for your domain | its secret |
| Local / preview / staging | 1x00000000000000000000BB (Cloudflare's always-pass key for invisible widgets) | 1x0000000000000000000000000000000AA |
The test keys work on any hostname, including localhost and Vercel preview URLs, and always
verify. (1x00000000000000000000AA is the visible-widget equivalent.) Never ship them to production.
Turnstile on the client
This package does not ship a Turnstile widget. Render it with @marsidev/react-turnstile in
invisible/execute mode, and post the token as token. The pattern below is the one used in
production on businessflow.co.za: it guards against the script never loading, retries widget
errors, resets on expiry, and unsticks the form if Cloudflare never answers.
'use client';
import { useRef, useState } from 'react';
import { Turnstile, type TurnstileInstance } from '@marsidev/react-turnstile';
// Module-level constant: an inline literal makes the widget re-render on every parent render.
// responseField:false stops the widget injecting a hidden <input name="cf-turnstile-response">
// into the form, which FormData below would otherwise post as a stray lead field.
const TURNSTILE_OPTIONS = { size: 'invisible', execution: 'execute', responseField: false } as const;
const MAX_TURNSTILE_RETRIES = 3;
const TURNSTILE_SAFETY_TIMEOUT_MS = 15_000;
type Lead = { firstName: string; lastName?: string; email: string; phone: string; comments: string };
export function QuickConnectForm() {
const turnstile = useRef<TurnstileInstance | null>(null);
const pending = useRef<Lead | null>(null);
const retries = useRef(0);
const safetyTimer = useRef<number | null>(null);
const loadedAt = useRef(Date.now());
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [done, setDone] = useState(false);
function clearSafetyTimer() {
if (safetyTimer.current !== null) {
window.clearTimeout(safetyTimer.current);
safetyTimer.current = null;
}
}
async function submitWithToken(token: string) {
clearSafetyTimer();
const data = pending.current;
pending.current = null;
if (!data) return;
try {
const res = await fetch('/api/lead', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ ...data, token, _t: loadedAt.current, _website: '' }),
});
if (!res.ok) throw new Error((await res.json()).error ?? 'Submission failed');
setDone(true);
} catch (e) {
setError(e instanceof Error ? e.message : 'Submission failed. Please try again.');
} finally {
setSubmitting(false);
}
}
function onTurnstileError() {
if (!pending.current) return;
retries.current += 1;
if (retries.current < MAX_TURNSTILE_RETRIES) {
setTimeout(() => { turnstile.current?.reset(); turnstile.current?.execute(); }, 1000);
return;
}
clearSafetyTimer();
pending.current = null;
retries.current = 0;
setSubmitting(false);
setError('The security check could not complete. Please try again or contact us directly.');
}
function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
const data = Object.fromEntries(new FormData(event.currentTarget)) as unknown as Lead;
// Script-load guard: a blocked network or privacy extension leaves the ref null, and
// execute() would silently no-op — tell the user instead of showing a dead button.
if (!turnstile.current) {
setError('The security check could not load. Please refresh and try again.');
return;
}
setError(null);
setSubmitting(true);
pending.current = data;
retries.current = 0;
turnstile.current.reset();
turnstile.current.execute();
// Safety timeout: if neither onSuccess nor onError fires, unstick the form. One timer per
// attempt — a stale timer from an earlier attempt must never cancel a newer one.
clearSafetyTimer();
safetyTimer.current = window.setTimeout(() => {
safetyTimer.current = null;
if (pending.current) {
pending.current = null;
setSubmitting(false);
setError('The security check timed out. Please try again.');
}
}, TURNSTILE_SAFETY_TIMEOUT_MS);
}
if (done) return <p>Thanks — we will be in touch shortly.</p>;
return (
<form onSubmit={onSubmit}>
<input name="firstName" required placeholder="Name" />
<input name="lastName" placeholder="Surname" />
<input name="email" type="email" required placeholder="Email" />
<input name="phone" type="tel" required placeholder="Phone (+27…)" />
<textarea name="comments" required placeholder="How can we help?" />
<Turnstile
ref={turnstile}
siteKey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY!}
options={TURNSTILE_OPTIONS}
onSuccess={(token) => { retries.current = 0; submitWithToken(token); }}
onError={onTurnstileError}
onExpire={() => turnstile.current?.reset()}
/>
<button type="submit" disabled={submitting}>{submitting ? 'Sending…' : 'Send'}</button>
{error && <p role="alert">{error}</p>}
</form>
);
}Turnstile tokens are single-use and expire after 300 s, so the form calls reset() +
execute() per submission rather than reusing a token.
Server route
// app/api/lead/route.ts
import { createBusinessFlowHandler } from '@businessflow/leads/server';
export const POST = createBusinessFlowHandler({
apiUrl: process.env.BUSINESS_FLOW_API_URL!,
apiKey: process.env.BUSINESS_FLOW_API_KEY!,
sourceUrl: process.env.NEXT_PUBLIC_SITE_URL,
turnstileSecret: process.env.TURNSTILE_SECRET_KEY,
});Using the generic handler directly:
import { createLeadHandler } from '@businessflow/leads/server';
export const POST = createLeadHandler({
turnstile: { secretKey: process.env.TURNSTILE_SECRET_KEY! },
onSubmit: async (lead) => { /* … */ return { success: true }; },
});verifyTurnstile(token, { secretKey }) and getTurnstileErrorMessage(codes) are also exported
for custom routes; the result carries hostname and action if you want to check them yourself.
File attachments (v2.5+)
Lets a visitor attach plans or documents to a lead. Files go direct from the browser to the BusinessFlow API, not through your Next.js function — that clears Vercel's 4.5 MB request-body cap. Your server route only mints a short-lived ticket, so the API key never reaches the browser.
Server-enforced limits: 10 MB per file (decimal), 5 files per ticket,
extensions .pdf .jpg .jpeg .png .dwg. The API also sniffs the leading bytes, so a
renamed executable is rejected regardless of its extension. Uploaded files are
malware-scanned; the dashboard only serves a file once it comes back clean.
1. Add the ticket route
// app/api/lead-upload-ticket/route.ts
import { createUploadTicketHandler } from '@businessflow/leads/server';
export const POST = createUploadTicketHandler();Requires BUSINESS_FLOW_API_URL and BUSINESS_FLOW_API_KEY (throws at construction if
either is missing). The handler throttles per visitor IP — without that, one scripted
visitor would spend your site's entire shared API-key budget, because the API sees only
your host's egress address.
2. Upload from the form
import { uploadLeadAttachments } from '@businessflow/leads/client';
const result = await uploadLeadAttachments(files, {
ticketUrl: '/api/lead-upload-ticket',
apiUrl: process.env.NEXT_PUBLIC_BUSINESS_FLOW_API_URL!,
// Thread the session's ticket back in on every later batch — see below.
existingTicket: ticket ? { token: ticket, usedSlots } : undefined,
onProgress: (fileIndex, pct) => setRowProgress(fileIndex, pct),
});Keep the whole form session on one ticket. Mint on the first file selection, then
pass existingTicket into every subsequent call. The API binds attachments to a lead
per ticket, so a submission carrying ids from two different tickets is rejected.
It never throws. Everything that fails comes back in result.failures, each entry
carrying index (maps to your UI row), a user-facing error, and permanent — true
for oversize/wrong-type/over-cap (offer no retry), false for network and 5xx (offer a
retry). Submit the lead even when every upload failed; losing the enquiry is far worse
than losing the file.
3. Submit the lead
await fetch('/api/lead', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name, email, phone, comments, token: recaptchaToken,
// Send all three together, or omit all three.
...(result.attachmentIds.length > 0 && {
attachmentIds: result.attachmentIds,
uploadTicket: result.ticket,
popiaConsentVersion: 'your-site-2026-07-v1',
}),
}),
});Consent is mandatory whenever attachmentIds is non-empty — the API rejects the
submission otherwise. Gate your consent checkbox on there being at least one file, and
clear it when the last file is removed.
Documentation
License
MIT
