Skip to content

Guide · Developer

PDF API webhooks: receiving async render notifications

When to use webhook_url instead of waiting for the PDF, and how to build a receiver that authenticates deliveries, acknowledges fast and ignores duplicates.

Updated 17 min readSublimePDF Team

By default a SublimePDF render is synchronous: you send HTML or a template ID with data, keep the connection open, and the PDF comes back in the response. Add a webhook_url to the request and the render becomes asynchronous: SublimePDF notifies that URL when the render finishes, so your process does not have to wait.

This guide covers when that is worth doing, what SublimePDF sends, and how to build the receiving end: an endpoint that verifies every delivery's signature, accepts each notification exactly once, answers quickly and does the real work in the background. The receiver below is a single Node.js file with no dependencies.

What SublimePDF sends

The webhook contract is part of the API reference and the API's OpenAPI document. It has been implemented and tested against local Cloudflare runtimes; deliveries from the deployed service have not been verified yet. Before relying on webhooks in production, send a real render with a webhook_url from a staging key and inspect what arrives.

DetailBehaviour
EndpointsPOST /html-to-pdf, POST /url-to-pdf and POST /templates/{id}/generate accept webhook_url
webhook_urlA public https URL up to 2,048 characters; private, loopback and internal addresses are rejected with 400
Immediate response202 with the job object (id, status: "queued") and a status_url; validation errors still return synchronously
Eventsjob.succeeded or job.failed, as JSON: { id, type, created, data: { job, download_url?, download_expires_at? } }
Getting the PDFdata.download_url is a signed link that works without an API key until it expires (at the latest when the job's output is deleted, 24 hours by default)
SignatureSublimePDF-Signature: v1=<hex HMAC-SHA256(secret, "<SublimePDF-Timestamp>.<raw body>")>, with your workspace's whsec_ secret
Other headersSublimePDF-Event-Id, SublimePDF-Event-Type, SublimePDF-Timestamp (Unix seconds), SublimePDF-Delivery-Attempt, User-Agent: SublimePDF-Webhooks/1
SuccessAny 2xx within 10 seconds; redirects are not followed
RetriesAfter 30 s, 2 min, 10 min, 30 min, 1 h, 3 h and 6 h; after 8 failed attempts the delivery is marked dead in the app and can be replayed
DuplicatesPossible. Retries and replays keep the same event ID and body, signed again with a fresh timestamp
ReconciliationGET /jobs/{id} returns the job's current status at any time

The signature proves that a delivery came from SublimePDF and was not changed. A per-job token in the URL, covered below, is optional defence in depth: it ties a delivery to one job you created, even if the workspace secret leaks.

Synchronous or webhook?

SituationBetter choice
A user clicks "Download invoice" and waitsSynchronous: the PDF is in the response
An AI agent tool call that needs a document reference nowSynchronous, inside the executor from the agent quickstart
Large reports where render time approaches your HTTP or function timeoutWebhook
Nightly or month-end batches of hundreds of documentsWebhook, so workers are not tied up waiting
Serverless functions with short execution limitsWebhook
No publicly reachable HTTPS endpoint (local scripts, private networks)Synchronous

Synchronous calls are simpler. You get the PDF or an error in one place, and the retry rules in the error handling guide cover failures. Choose webhooks when waiting is the problem, not by default.

How the flow works

  1. Your code creates a job record (for example, "invoice 1042, pending") with a webhook URL for that job.
  2. It sends the render request with that URL as webhook_url and an Idempotency-Key, and stores the SublimePDF job ID from the 202 response.
  3. When the render finishes, SublimePDF sends a signed job.succeeded or job.failed event to the URL.
  4. Your receiver verifies the signature (and, if you use one, the URL's token), marks the job as notified if it was still pending, stores the raw body, answers with a 200 and queues the job.
  5. A background worker reads the event, downloads the PDF from data.download_url before it expires, and updates your records.
curl -s https://api.sublimepdf.com/v1/html-to-pdf \
  -H "Authorization: Bearer $SUBLIMEPDF_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 6f1c2f9e-6a52-4e43-9d0b-2f8f6c1b7a10" \
  -d '{
    "html": "<!doctype html><h1>Quarterly report</h1>",
    "webhook_url": "https://app.example.com/webhooks/sublimepdf/3b0c3a8e-2f0e-4d55-9f8e-0c7d1d2b6a41?token=PER_JOB_TOKEN"
  }'

The 202 response looks like this (abridged):

{
  "id": "job_2kP8sW4nR7tY1qZ5xV3mB9",
  "object": "job",
  "status": "queued",
  "kind": "html",
  "mode": "async",
  "webhook": { "url": "https://app.example.com/webhooks/sublimepdf/3b0c3a8e-…?token=…", "status": "waiting" },
  "status_url": "https://api.sublimepdf.com/v1/jobs/job_2kP8sW4nR7tY1qZ5xV3mB9"
}

Give each job its own webhook URL (optional)

A webhook endpoint is a public URL that anyone on the internet can call. The signature check below is the primary defence. A different, unguessable URL for every job adds a second one that does not depend on the shared workspace secret. Put your job ID in the path and a random token in the query string, and store only a hash of the token:

import { createHash, randomBytes, randomUUID } from "node:crypto";
 
const PUBLIC_BASE = process.env.PUBLIC_BASE_URL ?? "https://app.example.com";
const jobs = new Map(); // stands in for your database
const sha256 = (s) => createHash("sha256").update(s).digest();
 
export function createJob(meta = {}) {
    const jobId = randomUUID();
    const token = randomBytes(32).toString("base64url"); // 256 bits, never stored in plain text
    jobs.set(jobId, { ...meta, tokenHash: sha256(token), status: "pending", deliveries: 0, createdAt: Date.now() });
    return { jobId, webhookUrl: `${PUBLIC_BASE}/webhooks/sublimepdf/${jobId}?token=${token}` };
}
 
console.log(createJob({ invoice: "INV-2026-0142" }).webhookUrl);

The same in Python, with the check:

import hashlib
import hmac
import secrets
import uuid
 
def create_job(store, public_base="https://app.example.com"):
    job_id = str(uuid.uuid4())
    token = secrets.token_urlsafe(32)  # 256 bits
    store[job_id] = {"token_hash": hashlib.sha256(token.encode()).digest(), "status": "pending"}
    return job_id, f"{public_base}/webhooks/sublimepdf/{job_id}?token={token}"
 
def is_authentic(store, job_id, token):
    job = store.get(job_id)
    if job is None:
        return False
    return hmac.compare_digest(hashlib.sha256(token.encode()).digest(), job["token_hash"])
 
store = {}  # stands in for your database
job_id, url = create_job(store)
token = url.split("token=", 1)[1]
print(url)
print(is_authentic(store, job_id, token), is_authentic(store, job_id, "guess"))  # True False

This gives you three properties at once. A forged request has to guess a 256-bit token. A stolen token only works for one job, which is already finished. And because the job ID comes from the URL, you never have to trust an ID inside the payload. Both versions compare hashes in constant time (timingSafeEqual, hmac.compare_digest) so response timing does not leak how much of a guess was right.

Tokens in URLs can end up in access logs. Keep the query string out of your web server and proxy logs for this route, or accept that a logged token is only good for one completed job. SublimePDF also stores the full webhook_url with the job and returns it in job objects and in the app, so anyone in your workspace with access to jobs can see it.

The receiver: verify, record once, answer, then work

This is the complete receiver. It needs Node.js 18 or later and no dependencies, reads the webhook secret from SUBLIMEPDF_WEBHOOK_SECRET, and includes the createJob function from the previous section. The downloadable receiver.mjs is the earlier token-only version, without the signature check:

/**
 * Webhook receiver pattern from /guides/pdf-webhooks-guide (Node.js 18+, no dependencies).
 *
 * It verifies the SublimePDF-Signature header over the raw body, checks an unguessable
 * per-job token in the webhook_url as a second factor, accepts each job's notification
 * once, answers immediately and processes in the background.
 *
 * The in-memory Maps stand in for your database and job queue.
 */
import http from "node:http";
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
 
const PUBLIC_BASE = process.env.PUBLIC_BASE_URL ?? "https://app.example.com";
const WEBHOOK_SECRET = process.env.SUBLIMEPDF_WEBHOOK_SECRET ?? ""; // whsec_..., from Settings → Webhooks
const MAX_BODY_BYTES = 256 * 1024;
const sha256 = (s) => createHash("sha256").update(s).digest();
 
export const jobs = new Map(); // jobId -> { tokenHash, status, deliveries, payload }
export const queue = [];
 
/** Call when you submit a render: store the job, send the returned URL as webhook_url. */
export function createJob(meta = {}) {
    const jobId = randomUUID();
    const token = randomBytes(32).toString("base64url"); // 256 bits, never stored in plain text
    jobs.set(jobId, { ...meta, tokenHash: sha256(token), status: "pending", deliveries: 0, createdAt: Date.now() });
    return { jobId, webhookUrl: `${PUBLIC_BASE}/webhooks/sublimepdf/${jobId}?token=${token}` };
}
 
function readBody(req) {
    return new Promise((resolve, reject) => {
        const chunks = [];
        let size = 0;
        req.on("data", (c) => {
            size += c.length;
            if (size <= MAX_BODY_BYTES) chunks.push(c); // past the limit: keep draining, stop storing
        });
        req.on("end", () => (size > MAX_BODY_BYTES ? reject(Object.assign(new Error("too large"), { status: 413 })) : resolve(Buffer.concat(chunks))));
        req.on("error", reject);
    });
}
 
/** SublimePDF-Signature: v1=<hex HMAC-SHA256(secret, "<timestamp>.<raw body>")>; timestamps older than 5 minutes are rejected. */
export function verifySignature(secret, headers, rawBody, toleranceSec = 300) {
    const ts = String(headers["sublimepdf-timestamp"] ?? "");
    const sig = String(headers["sublimepdf-signature"] ?? "");
    if (!secret || !/^\d+$/.test(ts) || Math.abs(Date.now() / 1000 - Number(ts)) > toleranceSec) return false;
    const expected = Buffer.from("v1=" + createHmac("sha256", secret).update(`${ts}.`).update(rawBody).digest("hex"));
    const got = Buffer.from(sig);
    return got.length === expected.length && timingSafeEqual(got, expected);
}
 
const reply = (res, status, body) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(body));
};
 
export async function handleWebhook(req, res) {
    const url = new URL(req.url, "http://localhost");
    const m = url.pathname.match(/^\/webhooks\/sublimepdf\/([0-9a-f-]{36})$/);
    if (!m) return reply(res, 404, { error: "not found" });
    if (req.method !== "POST") return reply(res, 405, { error: "method not allowed" });
 
    const job = jobs.get(m[1]);
    const token = url.searchParams.get("token") ?? "";
    // Same response for unknown job and wrong token, so the endpoint does not reveal which job IDs exist.
    if (!job || !timingSafeEqual(sha256(token), job.tokenHash)) return reply(res, 404, { error: "not found" });
 
    if (Number(req.headers["content-length"] ?? 0) > MAX_BODY_BYTES) return reply(res, 413, { error: "too large" });
    let raw;
    try {
        raw = await readBody(req);
    } catch (e) {
        return reply(res, e.status ?? 400, { error: "bad body" });
    }
    // Verify on the raw bytes, before any JSON parsing. Same 404 as above: reveal nothing.
    if (!verifySignature(WEBHOOK_SECRET, req.headers, raw)) return reply(res, 404, { error: "not found" });
 
    job.deliveries += 1;
    if (job.status !== "pending") {
        // Duplicate or late delivery: acknowledge so the sender stops retrying, but do nothing twice.
        return reply(res, 200, { received: true, duplicate: true });
    }
    job.status = "received"; // in a database: UPDATE ... SET status='received' WHERE id=? AND status='pending'
    job.payload = raw.toString("utf8"); // keep the raw body; interpret it in the worker
    queue.push(m[1]);
    reply(res, 200, { received: true });
    setImmediate(drainQueue); // respond first, work afterwards
}
 
let draining = false;
async function drainQueue() {
    if (draining) return;
    draining = true;
    while (queue.length) {
        const jobId = queue.shift();
        const job = jobs.get(jobId);
        await processNotification(job); // fetch/store the PDF, update records, notify users
        job.status = "processed";
    }
    draining = false;
}
 
/** Replace with your logic: JSON.parse(job.payload), check type, download data.download_url before it expires. */
export let processNotification = async (job) => {
    await new Promise((r) => setTimeout(r, Number(process.env.SIMULATED_WORK_MS ?? 0)));
};
export const setProcessor = (fn) => { processNotification = fn; };
 
if (import.meta.url === `file://${process.argv[1]}`) {
    const port = Number(process.env.PORT ?? 8787);
    http.createServer(handleWebhook).listen(port, () => console.log(`webhook receiver on http://127.0.0.1:${port}`));
}

The in-memory jobs map and queue array stand in for your database and job queue, and processNotification is where your own logic goes. Four decisions in this handler matter more than the code:

  • Answer before working. Downloading a PDF, writing it to storage and emailing a customer can take seconds. Many webhook senders treat a slow answer as a failure and send again. GitHub, for example, asks receivers to respond within 10 seconds and suggests a queue for the processing; Stripe's guidance is to return a 2xx before any complex logic. SublimePDF waits 10 seconds for an answer before counting the attempt as failed, so answer within a second or two.
  • Record the raw body. The signature covers the exact bytes, so verify before parsing, and parse in the worker, not in the handler. If the payload surprises you, the delivery is still stored.
  • Change state once. "Set to received only if still pending" is the whole duplicate defence. In SQL that is one conditional UPDATE whose affected-row count tells you whether this delivery won. That stays correct when two deliveries arrive at the same moment on two servers.
  • Acknowledge duplicates with 200. Rejecting a duplicate with an error invites the sender to retry it again.

Verify that a delivery is authentic

Treat every request to the webhook route as untrusted until it passes all of these:

  1. HTTPS only. SublimePDF accepts only https:// webhook URLs. Tokens and payloads must not cross the network in plain text.
  2. The signature. Recompute the HMAC over the timestamp and the raw body with your workspace secret, compare it with SublimePDF-Signature in constant time, and reject timestamps more than five minutes from your clock. A replayed or edited request fails here.
  3. Per-job token, if you use one. As above, compared in constant time against a stored hash.
  4. A job you are waiting for. The job must exist, belong to the expected account or tenant in your system, and still be pending. Anything else is a duplicate or a forgery.
  5. Treat the payload as data. Limit its size (the receiver rejects bodies over 256 KB). Fetch download_url only over HTTPS and only from your SublimePDF API host, so a forged payload cannot make your server request internal addresses.

The secret is the full whsec_ string, used as the HMAC key in UTF-8. Owners and admins of the workspace can reveal and rotate it in the app under Settings → Webhooks. There is one active secret per workspace, and rotation takes effect at once, including for retries that are still pending, so deploy the new secret to your receiver straight after rotating.

The verifier in Node.js 18 or later, the same function as in the receiver above:

import { createHmac, timingSafeEqual } from "node:crypto";
 
/** headers: lower-cased header map; rawBody: Buffer/string exactly as received. */
export function verifySublimePdfWebhook(secret, headers, rawBody, toleranceSec = 300) {
    const ts = headers["sublimepdf-timestamp"] ?? "";
    const sig = headers["sublimepdf-signature"] ?? "";
    if (!/^\d+$/.test(ts) || Math.abs(Date.now() / 1000 - Number(ts)) > toleranceSec) return false;
    const expected = Buffer.from("v1=" + createHmac("sha256", secret).update(`${ts}.`).update(rawBody).digest("hex"));
    const got = Buffer.from(sig);
    return got.length === expected.length && timingSafeEqual(got, expected);
}

And in Python 3.8 or later, standard library only. Pass the body as bytes exactly as received, for example request.get_data() in Flask or await request.body() in Starlette:

import hashlib, hmac, time
 
def verify_sublimepdf_webhook(secret: str, headers, raw_body: bytes, tolerance: int = 300) -> bool:
    ts = headers.get("SublimePDF-Timestamp", "")
    sig = headers.get("SublimePDF-Signature", "")
    if not ts.isdigit() or abs(time.time() - int(ts)) > tolerance:
        return False
    expected = "v1=" + hmac.new(secret.encode(), ts.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, sig)

headers must be case-insensitive, as it is in common Python web frameworks. Even after all five checks, keep the business decision with your own records. A notification that a render finished should move a job you created to the next state, not create new work from scratch.

Retries, duplicates and missing callbacks

Design for at-least-once delivery: a notification may arrive more than once, late, or out of order relative to other jobs. SublimePDF retries a delivery that did not get a 2xx within 10 seconds after 30 seconds, 2 minutes, 10 minutes, 30 minutes, 1 hour, 3 hours and 6 hours, so a delivery can arrive up to about ten hours after the render. After the 8th failed attempt it is marked dead and shown in the app under Settings → Webhooks, where you can replay it. Stripe's documentation describes the same model for its own events: endpoints "might occasionally receive the same event more than once", with no guaranteed order.

  • Duplicates are handled by the state change above. Retries and replays carry the same SublimePDF-Event-Id and the same body, so you can also de-duplicate on the event ID.
  • Order matters less when each job has its own record. Each job only moves forward (pending to received to processed), and a delivery for a job that has already moved on is acknowledged and ignored.
  • Failures in your worker are your retries, not the sender's. The handler already answered 200. If storing the PDF fails, retry the job from your queue. If the signed download_url has expired by then, download with GET /jobs/{id}/download and your API key while the output is still retained.
  • A callback that never arrives needs a deadline. Run a periodic sweep for jobs still pending after a time you choose, and read their status with GET /jobs/{id}. Re-submitting the render with the job's original Idempotency-Key returns the same job with 202 rather than rendering again.

Test the receiver locally

We ran the token-only receiver (receiver.mjs) on Node.js 24.5 with test deliveries, using a JSON body invented for the test. The results below are for that version; the signature check added above runs before the state change and does not affect them. SublimePDF's own backend tests verify its signed deliveries with the same Node.js verifier in a local test environment. The Python verifier accepted a signature produced by Node.js and by openssl and rejected an edited body and a wrong secret.

TestResult
First delivery with the correct token200, job queued, answered in 11 ms while the worker took 1.5 s
Same delivery again200 with duplicate: true, not queued again
Three simultaneous deliveries for another jobOne 200, two 200 duplicates, processed once
Wrong token, missing token, another job's token404
Unknown job ID404
GET instead of POST405
300 KB body413
After the worker ranBoth jobs processed exactly once

To repeat this yourself, save this script as try-receiver.mjs next to receiver.mjs and run node try-receiver.mjs. It starts the receiver on port 8787, creates one job and prints its webhook URL:

import http from "node:http";
import { createJob, handleWebhook } from "./receiver.mjs";
 
const port = Number(process.env.PORT ?? 8787);
http.createServer(handleWebhook).listen(port, "127.0.0.1", () => {
    // createJob builds URLs from PUBLIC_BASE_URL; for a local test, run with PUBLIC_BASE_URL=http://127.0.0.1:8787
    const { jobId, webhookUrl } = createJob({ invoice: "INV-2026-0142" });
    console.log(`job ${jobId}`);
    console.log(`WEBHOOK_URL='${webhookUrl}'`);
});
PUBLIC_BASE_URL=http://127.0.0.1:8787 node try-receiver.mjs
# in another terminal, paste the WEBHOOK_URL line it printed, then:
curl -i -X POST "$WEBHOOK_URL" -H "Content-Type: application/json" -d '{"test":"local"}'
curl -i -X POST "$WEBHOOK_URL" -H "Content-Type: application/json" -d '{"test":"local"}'   # duplicate

We also ran the receiver from this guide, with the signature check, on Node.js 24.5. Requests without a signature, signed with another secret, with a timestamp ten minutes old, or with one byte of the body changed got 404. A correctly signed request got 200, the same request again got a 200 duplicate, and the job was processed once. To send a signed request by hand, sign the body the way SublimePDF does:

BODY='{"id":"evt_local","type":"job.succeeded","created":0,"data":{}}'
TS=$(date +%s)
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$SUBLIMEPDF_WEBHOOK_SECRET" -hex | sed 's/^.* //')
curl -i -X POST "$WEBHOOK_URL" -H "Content-Type: application/json" \
  -H "SublimePDF-Timestamp: $TS" -H "SublimePDF-Signature: v1=$SIG" -d "$BODY"

Then test with real deliveries. Expose the receiver through a tunnelling service or a staging deployment with an HTTPS URL, use a staging API key (see the authentication guide), send one render with webhook_url, and record what arrives: headers, body and timing. The app's Settings → Webhooks page can also send a signed webhook.test event to a URL and lists every delivery with its attempts. Return a 500 deliberately once to see the first retry arrive about 30 seconds later.

Checklist

  • Webhooks are used where waiting is the problem; interactive and agent calls stay synchronous.
  • The receiver verifies SublimePDF-Signature over the raw body with the workspace secret and rejects timestamps more than five minutes old.
  • Optionally, every job gets its own HTTPS webhook URL with a 256-bit token; only the token's hash is stored.
  • The receiver checks job and state and limits body size.
  • Each delivery is stored raw, the job state changes once, and duplicates get a 200.
  • The handler answers within a second or two; a queue does the work and its own retries.
  • A sweep catches jobs whose callback never arrived and reads their status with GET /jobs/{id}.
  • Real staging deliveries have been inspected before production use.

For the endpoint list and request options, see the API reference. For how SublimePDF handles keys and request data, see the security page.

Sources

  1. GitHub Docs: Best practices for using webhooks · accessed 23 November 2026
  2. Stripe Docs: Receive Stripe events in your webhook endpoint · accessed 23 November 2026
  3. Node.js docs: crypto.timingSafeEqual · accessed 23 November 2026
  4. Python docs: secrets — generate secure random numbers for managing secrets · accessed 23 November 2026

Generate your first PDF with one API call.

Create an account, copy an API key and send HTML, or a template ID with JSON data, from your code or your agent.