Rendering a video takes longer than an HTTP request should stay open. If your product calls a video API inline and waits, you get timeouts, retries that double-charge, and users staring at a spinner tied to a single server process. The fix is a small async pipeline: start the job, return immediately, and finish the work when the result arrives.
This post builds that pipeline in Node.js against the PitchTwin API. The same pattern applies to any API that answers 202 Accepted and calls you back later.
How the async flow works
POST /generations never returns a video. It returns 202 with an id and status: "queued". The video is rendered in the background, and the result reaches you in one of two ways:
- Webhook. If you pass
webhook_url(it must be https), PitchTwin POSTs{ "type": "generation.succeeded" | "generation.failed", "data": {...} }to it, signed with aPitchTwin-Signature: t=…,v1=…header. - Polling.
GET /generations/:idreturns the currentstatusand, once it succeeds,video_url,audio_url,words,duration_msandtokens_charged.
Webhooks are delivered once. There is no retry, so a deploy, a crashed pod or a bug in your handler means a missed event. Treat the webhook as the fast path and polling as the safety net, and build both from day one.
The job table
Keep your own record of every generation. A minimal row:
| Column | Purpose |
|---|---|
id | Your job id |
generation_id | The id returned by POST /generations |
status | pending, succeeded or failed |
video_key | Where you stored the MP4 in your own storage |
error | Error from a failed generation |
created_at | Used by the reconciler |
In the code below, db and queue stand in for your data layer and job queue (Postgres, BullMQ, SQS, whatever you already run).
A small API client
const PT = "https://pitchtwin.ai/api/v1";
const KEY = process.env.PITCHTWIN_KEY!;
export async function pt(path: string, init: RequestInit = {}) {
const res = await fetch(PT + path, {
...init,
headers: {
Authorization: `Bearer ${KEY}`,
"Content-Type": "application/json",
},
});
const body = await res.json();
if (!res.ok) throw new Error(`${body.error?.code}: ${body.error?.message}`);
return body;
}
Keep the pt_live_… key on the server. Never call the API from a browser or a mobile app.
Starting a generation
Create the job row first, then call the API, then save the generation id. If the process dies between the last two steps, the reconciler can still find the job.
export async function startVideo(avatarId: string, text: string) {
const job = await db.jobs.insert({ status: "pending" });
const gen = await pt("/generations", {
method: "POST",
body: JSON.stringify({
avatar_id: avatarId,
text,
webhook_url: "https://your.app/hooks/pitchtwin",
}),
});
await db.jobs.update(job.id, { generation_id: gen.id });
return job.id;
}
Send exactly one of text, script or audio. A 402 with insufficient_tokens is worth handling explicitly, so your users see "top up" instead of a generic failure.
Receiving the webhook
Two rules matter here: verify the signature against the raw request body, and make the handler idempotent. Express parses JSON by default, which loses the exact bytes that were signed, so mount express.raw() on this route only.
import express from "express";
import crypto from "node:crypto";
const SECRET = process.env.PITCHTWIN_WEBHOOK_SECRET!;
function verify(raw: Buffer, header: string, toleranceSec = 300) {
const parts: Record<string, string> = {};
for (const piece of header.split(",")) {
const i = piece.indexOf("=");
if (i > 0) parts[piece.slice(0, i).trim()] = piece.slice(i + 1).trim();
}
const { t, v1 } = parts;
if (!t || !v1 || !/^\d+$/.test(t)) return false;
if (Math.abs(Date.now() / 1000 - Number(t)) > toleranceSec) return false;
const expected = crypto
.createHmac("sha256", SECRET)
.update(`${t}.`)
.update(raw)
.digest();
const given = Buffer.from(v1, "hex");
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}
const app = express();
app.post(
"/hooks/pitchtwin",
express.raw({ type: "application/json" }),
async (req, res) => {
if (!verify(req.body, req.get("PitchTwin-Signature") ?? "")) {
return res.status(400).send("invalid signature");
}
const event = JSON.parse(req.body.toString("utf8"));
await applyResult(event.type, event.data);
res.sendStatus(200);
}
);
The secret comes from Dashboard → API keys. Calling update() twice is the same as hashing the concatenation ${t}.${raw_body}, and it avoids decoding the body into a string before you have checked it. The full reasoning behind each line is in How to verify HMAC webhook signatures.
Keep the handler fast: write to the database, queue the slow work, return 2xx.
One function for both paths
The webhook and the reconciler both end up here, so the logic lives in one place and runs safely twice:
async function applyResult(type: string, g: any) {
const job = await db.jobs.findByGenerationId(g.id);
if (!job || job.status !== "pending") return; // unknown or already handled
if (type === "generation.succeeded") {
await db.jobs.update(job.id, { status: "succeeded" });
await queue.add("copy-video", { jobId: job.id, generationId: g.id });
} else if (type === "generation.failed") {
await db.jobs.update(job.id, { status: "failed", error: g.error });
}
}
In production, make the pending → succeeded transition a conditional update (UPDATE … WHERE status = 'pending') so two workers can't both win. Failed generations are refunded automatically, so there is no billing cleanup on your side: just show the user a useful message and let them retry.
Copy the video before the link expires
video_url and audio_url are signed links that expire after 24 hours. Don't store them as permanent URLs. A worker should fetch the generation again for a fresh link, then copy the MP4 into your own bucket:
async function copyVideo({ jobId, generationId }: { jobId: string; generationId: string }) {
const g = await pt(`/generations/${generationId}`);
const res = await fetch(g.video_url);
if (!res.ok) throw new Error(`download failed: ${res.status}`);
const key = `videos/${jobId}.mp4`;
await storage.put(key, Buffer.from(await res.arrayBuffer()), "video/mp4");
await db.jobs.update(jobId, { video_key: key });
}
If you need captions, save g.words at the same time. Captions from word timestamps shows how to turn it into WebVTT.
The reconciler
Because each webhook is sent once, run a periodic job that polls anything still pending:
setInterval(async () => {
const stale = await db.jobs.findPending({ olderThanMinutes: 10 });
for (const job of stale) {
if (!job.generation_id) continue; // see note below
const g = await pt(`/generations/${job.generation_id}`);
if (g.status === "succeeded" || g.status === "failed") {
await applyResult(`generation.${g.status}`, g);
}
}
}, 60_000);
Pick the age threshold based on the length of videos you generate; longer videos stay in progress longer. Treat any status other than succeeded or failed as still in progress rather than matching on a fixed list. Jobs with no generation_id crashed between the API call and the save; match them against GET /generations or mark them failed and let the user retry.
Checklist
- Job row written before the API call.
webhook_urlset on every generation.- Signature checked on raw bytes, with a timestamp tolerance and a constant-time compare.
- Handler idempotent and quick; slow work goes to a queue.
- Videos copied to your storage, never served from the 24-hour link.
- Reconciler polling stale jobs.
Try it
Sign up for 60 free tokens with no card, point webhook_url at a tunnel to your laptop, and fire a test generation. The quickstart has the three calls you need, and the webhooks reference covers the payload format.