leadpending-web
v0.1.2
Published
Collect visitor context and send website leads to LeadPending. Browser collector, server client, and client-side submission checks.
Maintainers
Readme
leadpending-web
Collect visitor context and send website leads to LeadPending. One small, zero-dependency package for every donor site: a browser collector, a server client, and lightweight client-side submission checks.
The complete ingest contract ships with the package in INTEGRATION.md and is
also published at https://leadpending.com/docs. This package is that contract
as code, so a field can't drift per site.
Install
npm install leadpending-webleadpending-web is ESM-only. Use it with import in a modern runtime or
bundler; CommonJS require() is not supported. Server-side use requires
Node.js 18.13 or newer.
Agent integration handoff
This README and the INTEGRATION.md shipped in the npm package are the
self-contained handoff for a coding agent. The website documentation is a
convenience, not a prerequisite for integration. Keep the browser/server
boundary below intact and use only the three public ESM entry points; do not
import files from dist.
After installation, hand the agent
node_modules/leadpending-web/INTEGRATION.md as the complete offline contract.
An integrating agent should make these changes in order:
- Install
leadpending-weband confirm the application has an ESM-capable runtime or bundler. Server code must run on Node.js 18.13 or newer. - Put
LEADPENDING_API_KEY=lp_live_…in the deployment's server-only secret store. Never expose it through browser-prefixed environment variables, rendered HTML, client bundles, logs, or form payloads. - In browser code, call
trackPageView()on each navigation. At submission, runcheckSubmission(), callcollectVisitor(), and send the result to the site's own server endpoint with the form fields. - Generate one idempotency key per user submission and reuse that same key for retries. Do not generate a new key inside a retry loop.
- In server-only code, construct
LeadPendingClient, pass the browser'svisitorblock through unchanged, and add only connection facts observed by the server (ip,userAgent, andcountry) through theconnectionoption. - Treat LeadPending as the only store for the acquisition-form payload. Do not insert, upsert, mirror, cache, or fall back to a local contact/application row or submission event. A separate product account may exist locally.
- During setup, call
validateLead()with a representative payload. It uses the real validation and normalization path without creating a lead or spending quota. Inspect the returned normalized fields and spam signals, then switch the production submission path tocreateLead(). - Handle request failures without leaking the API key or internal error data to the browser. Preserve the idempotency key when retrying an uncertain request.
Before handing the integration back, verify that the browser bundle contains
neither the API key nor LeadPendingClient, a normal form submission includes
the collected visitor journey, a filled honeypot is stopped client-side, the
dry run creates no lead, and two retries with one idempotency key do not create
duplicates. Also assert that accepted and failed submissions leave every local
contact/application table unchanged. The bundled INTEGRATION.md contains the
complete payload contract and reason codes when adapting fields or writing
fixtures.
The shape of an integration
The site API key (lp_live_…) is a server secret and must never reach the
browser. So the flow is always: the browser collects visitor context, hands it
to your server with the form, and your server forwards it to LeadPending.
1. In the browser — collect the visit
Call trackPageView() on every page so the journey accumulates, and
collectVisitor() when the form is submitted.
import { trackPageView, collectVisitor } from "leadpending-web/browser";
import { checkSubmission, newIdempotencyKey } from "leadpending-web";
// On every page load:
trackPageView();
// On submit:
const verdict = checkSubmission({
message: form.message.value,
honeypot: form.company_url.value, // a hidden field a real person leaves blank
elapsedMs: Date.now() - shownAt,
});
if (!verdict.ok) {
// Reject a bot or an empty message before it ever leaves the page.
return;
}
// Keep this value if your browser code retries the same submission.
const submissionId = newIdempotencyKey();
await fetch("/api/contact", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
submissionId,
name: form.name.value,
email: form.email.value,
message: form.message.value,
visitor: collectVisitor(), // journey, UTM, referrers, client context
}),
});2. On your server — forward to LeadPending
import { LeadPendingClient } from "leadpending-web/server";
const leadpending = new LeadPendingClient({
apiKey: process.env.LEADPENDING_API_KEY!,
});
export async function POST(request: Request) {
const form = await request.json();
try {
await leadpending.createLead(
{
email: form.email,
message: form.message,
name: form.name,
page_url: form.pageUrl,
visitor: form.visitor,
},
{
idempotencyKey: form.submissionId, // stable per submission → retry-safe
// Fields only the connection knows, layered onto the visitor block:
connection: {
ip: request.headers.get("x-real-ip") ?? undefined,
userAgent: request.headers.get("user-agent") ?? undefined,
country: request.headers.get("cf-ipcountry") ?? undefined,
},
},
);
return new Response(null, { status: 204 });
} catch (error) {
// A non-2xx or invalid 2xx is LeadPendingError; network and cancellation
// errors retain their original types. Return only a generic browser failure.
return new Response(null, { status: 502 });
}
}API
leadpending-web (runtime-agnostic)
checkSubmission(input)— honeypot, timing and content checks; returns{ ok: true }or{ ok: false, reason }.newIdempotencyKey(prefix?)— a URL-safe key with a unique 32-hex-character suffix. A custom prefix must contain 1–222 URL-unreserved ASCII characters (A–Z,a–z,0–9,.,_,~, or-).- Types:
LeadPayload,Visitor,JourneyStep,LeadResult,LeadPreview.
These checks are a separate browser preflight, not a copy of server spam scoring. They only classify — the decision to drop a submission stays with you. See Spam scoring for what the server does with a lead it accepts.
leadpending-web/browser
trackPageView(options?)— record the current page as a journey step; safe to call on every load. Persists insessionStoragefor the tab's lifetime.collectVisitor(options?)— build thevisitorblock from the tracked visit plus live browser context. It merges non-empty configured campaign values from the current URL over stored attribution without rewriting storage;utmKeys: []disables current-URL capture. Returnsundefinedoff the browser.
leadpending-web/server
new LeadPendingClient({ apiKey, baseUrl?, fetch? })client.createLead(payload, { idempotencyKey?, connection?, signal? })— returns the created (or replayed) lead; throwsLeadPendingErroron a non-2xx or malformed API response.client.validateLead(payload, { connection?, signal? })— a dry run: validates and normalizes the payload exactly as the real endpoint would, and returns aLeadPreview(the normalizedvisitor, the resolvedsubject, and thespam_score/spam_reasons) without creating a lead or spending quota. Use it in a test to prove a live key is accepted and to see which visitor fields survive normalization.
The client retries network failures, 429, and 5xx responses with one
idempotency key. An AbortError is never retried. If the supplied signal is
already aborted or aborts during retry backoff, the public call settles
immediately with its explicit signal.reason or an AbortError, and no next
request starts. A malformed successful API response fails closed with
LeadPendingError.code === "INVALID_RESPONSE" instead of returning an object
with missing identifiers.
Spam scoring
A submission is never rejected for looking like spam — it is scored and labeled,
and the operator decides. Every accepted lead carries a spam_score (0 to 1) and
spam_reasons, from two sources:
- E-mail deliverability — a free DNS check (MX, then A/AAAA) of the
recipient's domain. A domain that can receive no mail flags
recipient_domain_undeliverable. The check fails open: a slow or failed lookup never penalizes a lead. - Message content — cheap heuristics: very short, a single token, no letters, one repeated character. No single content signal convicts on its own.
Signals combine as independent probabilities and cross 0.5 when a lead is worth
suspicion. validateLead returns the same score, so you can calibrate before
going live. The full contract, with every reason code, is in the bundled
INTEGRATION.md and the matching
online integration doc.
What the server derives itself
The submitting server's own IP and country come from the connection and must
not be sent in the body. The connection option above is about the visitor
your server observed, not about your server.
License
MIT
