
- Premium Results
- Publish articles on SitePoint
- Daily curated jobs
- Learning Paths
- Discounts to dev tools
7 Day Free Trial. Cancel Anytime.
Automating Contract Signing in Node.js: Webhooks, Verification, and Storing Signed PDFs
By Derick Dorner
Sending a document for signature is the easy part of an e-signature integration. One POST request and the signer gets an email. The work that actually breaks in production happens afterwards: knowing when the document was signed, trusting the notification that told you so, handling the same notification twice, and getting the final PDF into storage before the download link expires.
This tutorial builds that whole loop in Node.js with Express. An event in your app (a deal is approved, a client is onboarded, a task moves to "ready to sign") sends a contract from a template. When the signer finishes, a webhook arrives, your server verifies it, and the signed PDF plus its audit trail get saved without anyone touching them.
The code uses Firma.dev, the e-signature API I work on, because I needed a real API to make the examples runnable. The patterns are not specific to it, though. Signature verification, idempotent handlers, short-lived download URLs, and reconciliation jobs show up in almost every webhook-driven integration, and the same structure applies whether you're receiving events from a payment processor, a CI system, or another signing provider.
What we're building
The flow has four parts:
- Send: your app calls the API to create a signing request from a template and send it.
- Receive: the provider POSTs an event to your webhook endpoint when something happens.
- Verify and dedupe: the endpoint checks the HMAC signature, rejects stale or forged requests, and ignores events it has already handled.
- Store: on completion, the worker fetches the signed PDF and the audit trail and writes them to storage.
There's a fifth part that tutorials usually skip: a reconciliation job that catches anything the webhooks missed. We'll build that too, because webhooks are a notification mechanism, not a delivery guarantee.
Prerequisites
- Node.js 20 or later (we use the built-in
fetchandcrypto) - Express 4
- An API key and a template with one signer role. Firma.dev workspaces come with a test key that doesn't consume credits and watermarks the output, which is what you want while building.
- A public HTTPS URL for local development. ngrok or Cloudflare Tunnel both work.
mkdir signing-demo && cd signing-demo
npm init -y
npm install express
Set three environment variables:
export SIGNING_API_KEY="your-test-api-key"
export SIGNING_WEBHOOK_SECRET="your-webhook-signing-secret"
export SIGNING_TEMPLATE_ID="your-template-id"
Step 1: a small API client that respects rate limits
Before sending anything, wrap the HTTP calls in one place. This is where authentication lives, and it's also where you handle 429 Too Many Requests once instead of in every caller. Most APIs, this one included, return a Retry-After header on a 429, so the client should honour it rather than guessing a backoff.
// client.js
const BASE_URL = 'https://api.firma.dev/functions/v1/signing-request-api';
const API_KEY = process.env.SIGNING_API_KEY;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export async function api(path, { method = 'GET', body, retries = 3 } = {}) {
for (let attempt = 0; attempt <= retries; attempt++) {
const res = await fetch(`${BASE_URL}${path}`, {
method,
headers: {
Authorization: API_KEY,
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
});
// 429 (rate limited) and 503 (resource still being generated) both
// tell us when to come back. Respect that instead of hammering.
if ((res.status === 429 || res.status === 503) && attempt < retries) {
const wait = Number(res.headers.get('retry-after') ?? 2) * 1000;
await sleep(wait);
continue;
}
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(`${method} ${path} failed with ${res.status}`);
err.status = res.status;
err.body = data;
throw err;
}
return data;
}
}
The 503 branch matters later. When a document has just been completed, the final PDF and its completion certificate take a moment to generate, and the download endpoint says so with a 503 and a Retry-After instead of handing you a half-built file.
Step 2: send a contract when something happens in your app
The trigger depends on your product. It might be a route handler, a queue consumer, or a CRM automation calling into your service. What matters is that the function doing the sending is small and takes plain data:
// send.js
import { api } from './client.js';
export async function sendContract({ clientName, firstName, lastName, email }) {
const signingRequest = await api('/signing-requests/create-and-send', {
method: 'POST',
body: {
template_id: process.env.SIGNING_TEMPLATE_ID,
name: `Engagement letter: ${clientName}`,
recipients: [
{
first_name: firstName,
last_name: lastName,
email,
designation: 'Signer',
order: 1,
},
],
},
});
// Persist this ID next to your own record (the deal, client, or task).
// Every later step, including reconciliation, keys off it.
return signingRequest.id;
}
Two design choices are worth calling out.
Use a single create-and-send call when you can. Many signing APIs split this into "create a draft" and "send the draft." That's useful when a human needs to review the document first, but for automation it creates a window where your process can crash between the two calls and leave an orphaned draft. A combined endpoint makes the operation atomic from your side.
Store the provider's ID on your own record immediately. Webhook payloads reference the signing request, not your deal or customer. Without that mapping you'll end up searching by email address, which falls apart as soon as one client signs two documents.
Step 3: receive the webhook, and keep the raw body
Here's the first place integrations quietly go wrong. Webhook signatures are computed over the exact bytes the sender transmitted. If Express parses the body as JSON first, you lose those bytes, and re-serialising the object won't reproduce them (key order, whitespace, and number formatting can all change). Signature checks then fail intermittently, which is the worst kind of failure.
The fix is to use express.raw() on the webhook route only, so the handler receives a Buffer:
// server.js
import express from 'express';
import { verifySignature } from './verify.js';
import { alreadyProcessed, markProcessed } from './store.js';
import { handleEvent } from './worker.js';
const app = express();
// JSON parsing for the rest of your app...
app.use('/api', express.json());
// ...but raw bytes for the webhook route.
app.post(
'/webhooks/signing',
express.raw({ type: 'application/json' }),
async (req, res) => {
const rawBody = req.body; // Buffer
if (!verifySignature(req.headers, rawBody, process.env.SIGNING_WEBHOOK_SECRET)) {
return res.status(401).send('invalid signature');
}
const event = JSON.parse(rawBody.toString('utf8'));
const eventId = event.id ?? req.get('x-firma-delivery');
if (await alreadyProcessed(eventId)) {
return res.status(200).send('duplicate, ignored');
}
await markProcessed(eventId);
// Acknowledge first, work second.
res.status(200).send('ok');
setImmediate(() => handleEvent(event).catch(console.error));
}
);
app.listen(3000, () => console.log('listening on :3000'));
Step 4: verify the HMAC signature properly
Most webhook providers sign payloads with HMAC-SHA256 using a shared secret. The details vary, so read your provider's docs for the exact header format, but the scheme here is common: the header looks like t=1731456000,v1=5f2b..., and the signed string is the timestamp, a dot, and the raw body. Stripe uses a very similar format, and the Standard Webhooks spec describes the same idea as a vendor-neutral convention.
// verify.js
import crypto from 'node:crypto';
const TOLERANCE_SECONDS = 300;
function parseHeader(header) {
if (!header) return null;
const parts = {};
for (const piece of header.split(',')) {
// Split on the first '=' only. Values can contain '=' in some schemes,
// and a naive split('=') silently truncates them.
const i = piece.indexOf('=');
if (i === -1) continue;
parts[piece.slice(0, i).trim()] = piece.slice(i + 1).trim();
}
return parts.t && parts.v1 ? parts : null;
}
function checkOne(header, rawBody, secret) {
const parsed = parseHeader(header);
if (!parsed) return false;
const timestamp = Number(parsed.t);
const age = Math.abs(Math.floor(Date.now() / 1000) - timestamp);
if (!Number.isFinite(timestamp) || age > TOLERANCE_SECONDS) return false;
const expected = crypto
.createHmac('sha256', secret)
.update(`${parsed.t}.`)
.update(rawBody)
.digest();
const received = Buffer.from(parsed.v1, 'hex');
// timingSafeEqual throws on length mismatch, so check first.
return (
received.length === expected.length &&
crypto.timingSafeEqual(received, expected)
);
}
export function verifySignature(headers, rawBody, secret) {
return (
checkOne(headers['x-firma-signature'], rawBody, secret) ||
// During secret rotation, the provider also signs with the previous
// secret for a grace period. Accept either.
checkOne(headers['x-firma-signature-old'], rawBody, secret)
);
}
Each line here defends against something specific.
- The timestamp check stops replay attacks. Without it, anyone who captures one valid request (from a log, a proxy, or a misconfigured tunnel) can resend it forever. Five minutes is a common tolerance; keep server clocks synced with NTP or legitimate requests will start failing.
crypto.timingSafeEqualcompares in constant time. A plain===on strings returns as soon as it hits a mismatched character, which in principle leaks how much of a guessed signature was correct. It also throws if the buffers differ in length, which is why the length check comes first.- Comparing bytes rather than hex strings avoids case-sensitivity bugs where one side produces uppercase hex.
- Checking the old-secret header lets you rotate secrets without downtime. Rotate the secret, deploy the new one, and events signed during the overlap still verify.
The OWASP guidance on cryptographic storage covers the other half of this: the secret belongs in an environment variable or secrets manager, never in the repository.
Step 5: make the handler idempotent
Every serious webhook system delivers at least once, not exactly once. If your endpoint is slow, returns a 5xx, or the network drops the response, the sender retries. Firma.dev, for example, makes up to three attempts per event (immediately, then after at least five minutes, then after at least an hour) and treats anything other than a 2xx as a failure, including redirects. Other providers retry more aggressively. Either way, your handler will eventually see the same event twice.
The defence is to record each event's unique ID and skip ones you've seen. In the server above that's alreadyProcessed and markProcessed. For a demo, a Set works:
// store.js (demo only)
const seen = new Set();
export const alreadyProcessed = async (id) => seen.has(id);
export const markProcessed = async (id) => { seen.add(id); };
In production, use your database and let a unique constraint do the work, so two concurrent deliveries can't both pass the check:
CREATE TABLE webhook_events (
event_id TEXT PRIMARY KEY,
received_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- INSERT ... ON CONFLICT DO NOTHING, then check the affected row count.
Also notice the order in the route: respond with 200, then do the work. Many providers time out deliveries after a few seconds (five, in this case). Downloading a PDF and uploading it to object storage can easily take longer than that, and a timeout counts as a failure, which triggers a retry, which triggers duplicate work. Acknowledging fast and processing asynchronously avoids that loop.
setImmediate is fine for a tutorial, but it has a real weakness: if the process dies after sending the 200 and before finishing the work, the event is acknowledged and lost. In production, push the event onto a durable queue (BullMQ, SQS, a jobs table) before responding. Step 7 covers the safety net for whatever still slips through.
Step 6: fetch and store the signed PDF and audit trail
Now the actual business logic. You'll usually see several event types (sent, viewed, a signer signed, declined, expired, completed). Only one of them means "the document is final":
// worker.js
import fs from 'node:fs/promises';
import path from 'node:path';
import { api } from './client.js';
const OUT_DIR = './signed';
export async function handleEvent(event) {
switch (event.type) {
case 'signing_request.completed':
return storeSignedDocument(event.data.signing_request.id);
case 'signing_request.recipient.declined':
case 'signing_request.expired':
// Flag the record in your app so a human can follow up.
console.log(`Needs attention: ${event.type}`, event.data?.signing_request?.id);
return;
default:
return; // Ignore everything else.
}
}
export async function storeSignedDocument(signingRequestId) {
// 1. Ask for a download link. The client retries on 503 while the
// final PDF and completion certificate are still being generated.
const download = await api(`/signing-requests/${signingRequestId}/download`);
// 2. The URL is pre-signed and short-lived. Fetch it now; don't store it.
const pdfRes = await fetch(download.download_url);
if (!pdfRes.ok) throw new Error(`PDF fetch failed: ${pdfRes.status}`);
const pdf = Buffer.from(await pdfRes.arrayBuffer());
// 3. Keep the audit trail alongside the document.
const audit = await api(`/signing-requests/${signingRequestId}/audit`);
await fs.mkdir(OUT_DIR, { recursive: true });
await fs.writeFile(path.join(OUT_DIR, `${signingRequestId}.pdf`), pdf);
await fs.writeFile(
path.join(OUT_DIR, `${signingRequestId}.audit.json`),
JSON.stringify(audit, null, 2)
);
}
Three things in here are easy to get wrong.
Don't treat "a signer signed" as "the document is done." With multiple signers, each one triggers its own event, and a per-signer "all complete" flag can be true on more than one of them. Key your storage logic off the single completion event.
Don't persist the download URL. Pre-signed URLs expire (this one carries an expires_at). Saving the link to your database and serving it to users later produces broken links a few minutes or hours later. Download the bytes and store them in storage you control. Swapping the fs.writeFile calls for an S3 PutObject or a Google Drive upload is a drop-in change.
Store the audit trail, not just the PDF. If a signature is ever disputed, the PDF shows what was signed, and the audit trail shows who signed it, when, and from where (timestamps, IP addresses, the sequence of views and signatures). That evidence is what makes an electronic signature defensible, which brings us to the legal side.
Step 7: reconcile, because webhooks will eventually miss
Retries are finite. Endpoints go down during deploys. Some providers auto-disable a webhook after enough consecutive failures, and events aren't guaranteed to arrive in order. Any one of these can leave a completed document sitting unsaved.
A small scheduled job closes that gap. Keep a list of signing requests your app considers "pending," and periodically ask the API for their real status:
// reconcile.js
import { api } from './client.js';
import { storeSignedDocument } from './worker.js';
import { getPendingSigningRequestIds, markStored } from './db.js'; // your code
export async function reconcile() {
for (const id of await getPendingSigningRequestIds()) {
const sr = await api(`/signing-requests/${id}`);
if (sr.status === 'finished') { // check your provider's completed status value
await storeSignedDocument(id);
await markStored(id);
}
}
}
// Run every 15 minutes with cron, a scheduler, or setInterval in a worker.
Since storeSignedDocument overwrites by ID, running it twice for the same document is harmless. That's the property you want from every step in a webhook pipeline: doing it again shouldn't change the result.
A short note on the legal side
None of this is legal advice, but a few facts shape how you build.
In the US, the ESIGN Act and the Uniform Electronic Transactions Act (adopted by 49 states) give electronic signatures the same legal standing as handwritten ones for most commercial documents. ESIGN also has requirements around consumer consent and record retention, which is part of why you store the final PDF yourself rather than relying on a third-party link.
In the EU, eIDAS defines three levels: simple (SES), advanced (AdES), and qualified (QES). SES and AdES cover most business contracts. QES requires a qualified trust service provider and certificate-based identity, and some documents (certain property transfers and court filings, depending on the country) require it or exclude e-signatures entirely. Check which level your document types need before you pick a provider, since not every API offers every level.
Across jurisdictions, the evidence that holds up is the same: who signed, how they were identified, when it happened, and proof the document hasn't changed since. That's the audit trail and the completion certificate, which is why Step 6 stores both.
Things to check when choosing a signing API
If you're evaluating providers for a workflow like this, the questions that matter at the integration level are mostly not on the pricing page:
- Is there a test mode that doesn't send real emails or consume credits?
- How are webhooks signed, and does verification support secret rotation without downtime?
- What are the retry semantics, and does each event carry a unique ID for deduplication?
- Can you query status directly, so you can reconcile when webhooks fail?
- How do you get the final document, and does the completed file include a certificate or audit trail?
- Which eIDAS levels does it support if you have EU signers?
- How does pricing scale with your volume? Per-seat, per-envelope, and monthly-minimum models behave very differently at 50 documents a month versus 50,000.
Conclusion
The send call is one line. The reliability comes from everything around it: keeping the raw body for verification, checking timestamps and comparing in constant time, acknowledging fast and deduplicating by event ID, downloading files before their links expire, and running a reconciliation job for the events that never arrive. Get those right and contract signing becomes something your app does in the background, with no one chasing signatures or copying PDFs between folders.
For the Firma.dev-specific details used here (event names, header format, rate limits), see the webhooks guide.
