Skip to content

Guide · Node.js (TypeScript)

Async PDF rendering with a verified webhook in Node.js (TypeScript)

A long report should not hold an HTTP request open. In async mode the API answers at once with a queued render and calls your endpoint when the PDF is ready. This guide has both halves in Node.js (TypeScript): the request, and a receiver that accepts only deliveries Formfeed really signed.

Free plan with 100 units a month, no credit card

What you need

  • An API key. Create one in the app under API keys and export it as FORMFEED_API_KEY. A test key (ff_test_…) is right for trying things out. See the quick start.
  • Node.js (TypeScript). You need Node.js 22 or newer and the @formfeed/sdk package, which has no dependencies of its own.
  • The template. revenue-report from the report example, and its data.json next to the program.
  • A secret. 16 to 200 random characters in FORMFEED_WEBHOOK_SECRET, known to both programs. It signs the deliveries of this render, retries included.
  • A public URL. Replace https://example.com/hooks/formfeed with your endpoint. While developing, formfeed listen forwards deliveries to localhost without a tunnel.
InstallShell
npm install @formfeed/sdk
npm install --save-dev tsx   # runs the .ts file directly

The program

The request names the template, switches to mode: "async" and says where to report. The answer comes back immediately with the status queued.

render.tsTypeScript
import { readFile } from 'node:fs/promises';
import { Formfeed } from '@formfeed/sdk';

const formfeed = new Formfeed({ apiKey: process.env.FORMFEED_API_KEY! });
const data = JSON.parse(await readFile('data.json', 'utf8'));

// a problem answer (4xx, 5xx) throws a FormfeedError with the API's code, title and detail
const render = await formfeed.renders.create({
  template: 'revenue-report',
  data,
  mode: 'async',
  webhook_url: 'https://example.com/hooks/formfeed',
  webhook_secret: process.env.FORMFEED_WEBHOOK_SECRET!,
});
console.log(render.id, render.status); // queued: the webhook reports the rest

Run it

It prints the render’s id and queued. A few seconds later your endpoint receives render.completed with the full render, its download_url included, or render.failed with the reason.

Shell
export FORMFEED_API_KEY=ff_test_...
export FORMFEED_WEBHOOK_SECRET=$(openssl rand -hex 24)
npx tsx render.ts

What is particular about Node.js (TypeScript)

  • Top-level await. The file uses await outside a function, so it must be an ES module: keep "type": "module" in package.json or name it .mts.
  • Retries are built in. The SDK sends an Idempotency-Key with every render and retries 429, 503 and network errors up to three times with backoff, with the same key: a retry of a request that was answered already gets that answer back instead of a second render.
  • Errors are typed. A problem answer throws a FormfeedError whose code is the API’s error code (template_not_found, quota_exceeded, …); catch it where you would show the user something useful.
  • Runs anywhere fetch does. The SDK uses only web APIs, so the same call works in Deno, Bun and Cloudflare Workers; only the file access differs.

The receiver

It listens on port 8080, reads the raw body, checks the signature and the age of the timestamp, and only then looks at the JSON. A delivery that fails the check gets 401.

hook.tsTypeScript
import { createServer } from 'node:http';
import { parseWebhookEvent } from '@formfeed/sdk';

const secret = process.env.FORMFEED_WEBHOOK_SECRET!;

createServer(async (request, response) => {
  // the signature covers the bytes on the wire: read the raw body, never re-serialised JSON
  const chunks: Buffer[] = [];
  for await (const chunk of request) chunks.push(chunk as Buffer);
  const body = Buffer.concat(chunks).toString('utf8');

  try {
    // checks the HMAC and the five-minute tolerance, throws when either fails
    const event = await parseWebhookEvent(secret, request.headers['webhook-signature'] as string, body);
    const render = event.data as { id: string; download_url: string | null };
    if (event.type === 'render.completed') console.log('done', render.id, render.download_url);
    if (event.type === 'render.failed') console.error('failed', render.id);
    response.writeHead(204).end();
  } catch {
    response.writeHead(401).end();
  }
}).listen(8080);

Start the receiver

Shell
FORMFEED_WEBHOOK_SECRET=… npx tsx hook.ts

Verifying in Node.js (TypeScript)

  • One call verifies. parseWebhookEvent checks the HMAC and the five-minute tolerance with Web Crypto and throws when either fails.
  • In Express. Mount express.text({ type: "application/json" }) on the webhook route: it keeps the body as the string that was signed, which is what parseWebhookEvent takes. With express.json() the body is already parsed and the signature can no longer be checked.

What arrives

A POST with Webhook-Signature: t=<unix seconds>,v1=<hex>, where the hex is HMAC-SHA256 over t, a dot and the raw body, keyed with your secret exactly as you have it, as UTF-8 bytes: the webhook_secret you sent, or a registered endpoint’s whole whsec_… string, prefix included. Every attempt is signed anew with its own t. Webhook-Id stays the same across retries, so it is your deduplication key. data is the render as GET /renders/{id} returns it:

POST /hooks/formfeedJSON
{
  "id": "evt_5b0c8e6f2d4a4c3e9b1a7f6e5d4c3b2a",
  "type": "render.completed",
  "created_at": "2026-09-18T10:42:00Z",
  "workspace_id": "3a6f…",
  "data": {
    "id": "rnd_7da09ab6cd9946b798c187c2a9350852",
    "status": "succeeded",
    "download_url": "https://cdn.formfeed.dev/o/eu/…/document.pdf?exp=…&sig=…",
    "page_count": 2,
    "units": 1,
    …
  }
}

Retries, and what your endpoint owes

  • Answer fast. A delivery succeeds with a 2xx within 10 seconds. Store the event and do the work afterwards.
  • Retries. Anything else, a redirect included, is retried after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours: six attempts in all, over about 14 hours and 40 minutes. The same event can therefore arrive twice: deduplicate by Webhook-Id.
  • Without a secret. A webhook_url without webhook_secret is delivered unsigned. For signed deliveries of every render, register an endpoint once in the app or through POST /webhooks; it gets its own secret.
  • Try it locally. formfeed listen --forward-to http://localhost:8080/hooks/formfeed relays the events of your test renders to your machine, signed with the session’s own secret rather than webhook_secret: start the receiver with that one, which formfeed listen --print-secret prints (run it before the session, since it ends a running one). formfeed trigger render.completed --template revenue-report makes a real test render whose event you watch arrive. The key needs the webhook:listen scope. See developing webhooks locally.

When the API says no

  • One shape for every error. Errors are problem documents (RFC 9457) with type, title, status, detail, a stable code and the request_id to quote to support; the type URL leads to a page about that error. The list is in the error reference.
  • The usual ones. 401 unauthorized for a missing or revoked key, 404 template_not_found for a wrong template name, 422 template_runtime_error when the template fails on the data, 429 rate_limited above the plan’s requests per second, 402 quota_exceeded when the Free plan’s units are used up (a paid plan bills extra units up to its hard cap).
  • Retry safely. Send an Idempotency-Key header with the POST, and repeat the request with the same key when you do not know whether the first attempt arrived: for 24 hours the key returns the first answer instead of rendering and billing again. The answer is stored once the first attempt has been answered, so do not retry while it may still run; and problems below 500 are stored too, so a corrected request needs a new key.

The job around this program

This guide is one program. What the job needs around it, from the template to the limits and the price, is on the page Report PDF generation.

More Node.js (TypeScript) guides

FAQ

Can I poll instead of receiving a webhook?
Yes: GET /renders/{id} until the status is succeeded or failed; the SDKs have waitFor and wait_for for it. A webhook saves the requests and reports sooner. See async and batch.
Why must the raw body be used?
The signature covers the bytes on the wire. Parsing and re-serialising JSON may reorder keys, change number formats or escape characters differently, and the HMAC of that text no longer matches.
What is the five-minute tolerance for?
It stops a captured delivery from being replayed later. It also means the clock of your server must be roughly right.

Async render with a webhook in other languages

Start rendering today

The free plan includes 100 units a month and free test renders. Change plans when you need more.