To parse invoices and bank statements in JavaScript (Node.js), POST the PDF to /v1/parse with fetch and FormData. It costs $0.02 a page with 50 pages free, and our 1-page test invoice passed 8 of 8 checks.

Parse invoices and bank statements in JavaScript

The program below runs on Node.js 22 with no packages to install. It uploads a PDF, waits for the job (an invoice takes under 20 seconds), prints the verification result, saves the Excel and CSV files and checks the signature on each webhook event.

Updated

What you need

You need Node.js 22 and an API key from API keys in the dashboard; signing in with Google gives you $1 of free credit, good for 50 pages. There is nothing to install: fetch, FormData and Blob are built into Node.js 22, and the script uses node:crypto and node:http from the standard library. Save the code below as parserkit-example.mjs and set your key in PARSERKIT_API_KEY. Run it on a server, never in a browser, so the key stays secret. Set PARSERKIT_WEBHOOK_URL to get a webhook for each job, and PARSERKIT_WEBHOOK_SECRET for the receiver.

The program

Run node parserkit-example.mjs parse <file> [preset] to parse a document, or node parserkit-example.mjs serve <port> to start the webhook receiver. The preset defaults to invoice; pass bank_statement for a bank statement. When parsing, the script reads the file from disk and sends it as multipart form data to https://api.parserkit.com/v1/parse?wait=25, with Authorization: Bearer <key> and a random UUID as Idempotency-Key. It polls if the job is still running, prints the verification result and a summary of the fields, and saves the spreadsheets.

parserkit-example.mjs
// Parse a document with the parserkit API, save its Excel and CSV files, and check webhook signatures.
//   node parserkit-example.mjs parse invoice.pdf [preset]
//   node parserkit-example.mjs serve 8000
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { basename } from "node:path";

const API = "https://api.parserkit.com";
const MAX_ATTEMPTS = 5;
const MAX_WAIT_S = 60;
const MAX_BODY_BYTES = 10 * 1024 * 1024;

class ParserkitError extends Error {
  constructor(status, error, requestId, jobId) {
    super(`${status} ${error.code}: ${error.message} (request_id ${requestId}, job ${jobId})`);
    this.status = status;
    this.code = error.code;
    this.requestId = requestId;
    this.jobId = jobId;
  }
}

const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

// Sends one request, waiting out 429 and 503 answers for as long as Retry-After asks
async function send(url, init = {}) {
  for (let attempt = 1; ; attempt++) {
    let response;
    try {
      response = await fetch(url, { ...init, signal: AbortSignal.timeout(90_000) });
    } catch (error) {
      if (attempt === MAX_ATTEMPTS) throw error;
      console.log(`network error (${error.name}), retrying in 2 s`);
      await sleep(2);
      continue;
    }
    if (response.status < 400) return response;

    const text = await response.text();
    const isJson = (response.headers.get("content-type") ?? "").startsWith("application/json");
    const body = isJson ? JSON.parse(text) : {};
    const waitS = Number(response.headers.get("retry-after") ?? 0);
    const retryable = (response.status === 429 || response.status === 503) && !body.job;
    if (retryable && waitS > 0 && waitS <= MAX_WAIT_S && attempt < MAX_ATTEMPTS) {
      console.log(`${response.status} ${body.error?.code}, retrying in ${waitS} s`);
      await sleep(waitS);
      continue;
    }
    const requestId = body.error?.request_id ?? response.headers.get("request-id");
    throw new ParserkitError(response.status, body.error ?? {}, requestId, body.job?.id ?? null);
  }
}

async function parse(path, preset) {
  const auth = { Authorization: `Bearer ${process.env.PARSERKIT_API_KEY}` };
  const form = new FormData();
  form.append("file", new Blob([await readFile(path)]), basename(path));
  form.append("preset", preset);
  if (process.env.PARSERKIT_WEBHOOK_URL) form.append("webhook_url", process.env.PARSERKIT_WEBHOOK_URL);

  // One key for this upload, sent again on every retry, so the API never starts a second job
  let response = await send(`${API}/v1/parse?wait=25`, {
    method: "POST",
    headers: { ...auth, "Idempotency-Key": randomUUID() },
    body: form,
  });

  // 202 means the job is still running. GET holds each call up to 25 s and answers 200 whatever the status, so we watch the status
  let job = await response.json();
  let waitS = Number(response.headers.get("retry-after") ?? 2);
  while (job.status === "queued" || job.status === "running") {
    console.log(`${response.status} ${job.id} is ${job.status}, checking again in ${waitS} s`);
    await sleep(waitS);
    response = await send(`${API}/v1/jobs/${job.id}?wait=25`, { headers: auth });
    job = await response.json();
    waitS = 2;
  }

  if (job.status === "failed") throw new ParserkitError("failed", job.error, response.headers.get("request-id"), job.id);
  return job;
}

function report(job) {
  console.log(`${job.id}: ${job.status}, ${job.pages} page(s), $${job.cost_usd}`);
  if (job.data_omitted) {
    console.log(`verification: ${job.verification_status}, the full result is at data_url`);
    return;
  }

  const { status, coverage, checks } = job.verification;
  const passed = checks.filter((check) => check.status === "pass");
  console.log(`verification: ${status}, ${coverage.checked} of ${coverage.values} values checked`);
  console.log(`checks: ${passed.length} of ${checks.length} pass`);
  for (const check of checks) {
    if (check.status !== "pass") console.log(`  ${check.status} ${check.kind} ${check.path}: ${check.message}`);
  }

  const data = job.data;
  if (job.preset === "bank_statement") {
    console.log(
      `${data.bank.name}, ${data.period_start} to ${data.period_end}: ${data.transactions.length} transactions,` +
        ` opening ${data.opening_balance}, closing ${data.closing_balance} ${data.currency}`,
    );
  } else {
    console.log(
      `invoice ${data.invoice_number} from ${data.vendor.name}, ${data.issue_date}:` +
        ` ${data.line_items.length} lines, total ${data.grand_total} ${data.currency}`,
    );
  }
  for (const warning of job.warnings) console.log(`warning ${warning.code}: ${warning.message}`);
}

async function download(job, names = ["output.xlsx", "output.csv"]) {
  for (const output of job.outputs) {
    if (!names.includes(output.name)) continue;

    // Signed links need no API key; keep them out of your logs
    const content = Buffer.from(await (await send(output.url)).arrayBuffer());
    const target = `${job.id}-${output.name}`;
    await writeFile(target, content);
    console.log(`saved ${target} (${content.length} bytes)`);
  }
}

export function verifySignature(secret, rawBody, header, toleranceS = 300) {
  const parts = Object.fromEntries(header.split(",").map((part) => part.split("=", 2)));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > toleranceS) return false;

  const expected = Buffer.from(createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest("hex"));
  const given = Buffer.from(parts.v1 ?? "");
  return expected.length === given.length && timingSafeEqual(expected, given);
}

function serve(port) {
  const secret = process.env.PARSERKIT_WEBHOOK_SECRET;
  if (!secret) throw new Error("set PARSERKIT_WEBHOOK_SECRET first");

  const server = createServer(async (request, response) => {
    try {
      const chunks = [];
      let size = 0;
      for await (const chunk of request) {
        size += chunk.length;
        if (size > MAX_BODY_BYTES) {
          console.log("oversized body, answered 413");
          response.writeHead(413, { Connection: "close" }).end();
          return;
        }
        chunks.push(chunk);
      }
      const rawBody = Buffer.concat(chunks);

      const header = request.headers["parserkit-signature"] ?? "";
      if (!verifySignature(secret, rawBody, header)) {
        console.log("signature check failed, answered 401");
        response.writeHead(401).end();
        return;
      }

      const event = JSON.parse(rawBody);
      const { "idempotency-key": eventId, "parserkit-attempt": attempt } = request.headers;
      console.log(`signature ok: ${event.type} ${event.data?.id} (${eventId}, attempt ${attempt})`);
      response.writeHead(200).end();
    } catch (error) {
      // A client that hangs up mid-body must not take the server down
      console.log(`delivery failed (${error.code ?? error.name}), answered 500`);
      if (!response.headersSent) response.writeHead(500);
      response.end();
    }
  });
  server.listen(port, () => console.log(`listening on port ${port}`));
}

const [command, arg, preset = "invoice"] = process.argv.slice(2);
if (command === "parse" && arg) {
  try {
    const job = await parse(arg, preset);
    report(job);
    await download(job);
  } catch (error) {
    if (!(error instanceof ParserkitError)) throw error;
    console.error(`parserkit error ${error.message}`);
    process.exit(1);
  }
} else if (command === "serve" && arg) {
  serve(Number(arg));
} else {
  console.error("usage: node parserkit-example.mjs parse <file> [preset] | serve <port>");
  process.exit(2);
}

Run it

A one-page invoice finishes in under 20 seconds, so the first POST answers 200 right away. The job costs $0.02 for 1 page, and verification.status comes back verified when every check passes.

Terminal
$ node parserkit-example.mjs parse invoice-quillfeather-0923.pdf
job_ygcsdn66uugqna8isima: succeeded, 1 page(s), $0.02
verification: verified, 35 of 35 values checked
checks: 8 of 8 pass
invoice QF-0923 from Quillfeather Studio Ltd, 2026-11-05: 4 lines, total 3147 GBP
saved job_ygcsdn66uugqna8isima-output.xlsx (10099 bytes)
saved job_ygcsdn66uugqna8isima-output.csv (532 bytes)
Fields the program reads from the job
FieldWhat it holdsOur run
statusqueued, running, succeeded or failedsucceeded
verification.statusverified, partial, unverified or discrepancyverified
verification.coverageValues read and values with a check35 and 35
verification.checksOne entry per check, with kind, path, status and message8, all pass
dataThe fields read from the documentinvoice QF-0923, total 3147 GBP
outputsSigned links to the files5 files
warningsAnything the parser flaggednone
cost_usdWhat the job cost0.02
The same job, trimmed
{
  "id": "job_ygcsdn66uugqna8isima",
  "status": "succeeded",
  ...
  "cost_usd": 0.02,
  "verification_status": "verified",
  ...
  "verification": {
    "status": "verified",
    "math_balanced": true,
    "coverage": {
      "values": 35,
      "checked": 35
    },
    "checks": [
      {
        "kind": "line_total",
        "path": "line_items[0].total",
        "fields": [
          "line_items[0].quantity",
          "line_items[0].unit_price",
          "line_items[0].total"
        ],
        "status": "pass",
        "expected": 1260,
        "actual": 1260,
        "difference": 0,
        "page": 1,
        "message": "quantity x unit price"
      },
      ...
      {
        "kind": "sum",
        "path": "grand_total",
        "fields": [
          "line_items[].total",
          "tax_total",
          "subtotal",
          "grand_total"
        ],
        "status": "pass",
        "expected": 3147,
        "actual": 3147,
        "difference": 0,
        "page": 1,
        "message": "the line totals + tax"
      }
    ],
    "repairs": [],
    "barcodes": []
  },
  ...
  "warnings": []
}

Trimmed with ...: the other job fields and the other checks.

The wait query parameter can be 0 to 60 seconds (default 60). Our job finished inside the 25 second window we asked for, so the POST returned 200 with the full job. If a job takes longer, the POST returns 202 with a Location header and Retry-After: 2. The script then calls GET /v1/jobs/{id}?wait=25, which holds the connection up to 25 seconds and answers 200 with the job whatever its status. It repeats the GET while status is queued or running and stops with the error code if it is failed.

Excel and CSV files

The job's outputs list holds 5 files: output.json, output.xlsx, output.csv, quickbooks.csv and xero.csv, each with a signed url and an expires_at time. The signed links do not need your API key and last at least an hour, so keep them out of your logs. For very large results, the API sets data_omitted to true and gives a data_url link instead of inline data; the program then prints the verification status and stops.

outputs, from the same job
[
  ...
  {
    "name": "output.xlsx",
    "bytes": 10099,
    "url": "https://files.parserkit.com/f/7d/acct_.../job_ygcsdn66uugqna8isima/out/output.xlsx?exp=1794051600&sig=...",
    "expires_at": "2026-11-07T11:40:00.000Z"
  },
  {
    "name": "output.csv",
    "bytes": 532,
    "url": "https://files.parserkit.com/f/7d/acct_.../job_ygcsdn66uugqna8isima/out/output.csv?exp=1794051600&sig=...",
    "expires_at": "2026-11-07T11:40:00.000Z"
  },
  ...
]

Trimmed to the two files the program saves. The signature in each link and the account id are replaced with ...

job_ygcsdn66uugqna8isima-output.csv
invoice_number,issue_date,due_date,vendor.name,currency,description,quantity,unit_price,total
QF-0923,2026-11-05,2026-11-19,Quillfeather Studio Ltd,GBP,"Poster illustration, A2, designs",3,420.00,1260.00
QF-0923,2026-11-05,2026-11-19,Quillfeather Studio Ltd,GBP,"Programme layout, pages",24,35.00,840.00
QF-0923,2026-11-05,2026-11-19,Quillfeather Studio Ltd,GBP,"Ticket artwork revisions, hours",6.5,55.00,357.50
QF-0923,2026-11-05,2026-11-19,Quillfeather Studio Ltd,GBP,"Print-ready file preparation, hours",3,55.00,165.00

As saved by the run, without the UTF-8 byte order mark at the start of the file.

Errors and retries

Send a typo in the preset, like invices, and the API answers 400 with error.code set to INVALID_REQUEST, an error.message listing the valid presets (invoice, receipt, bank_statement, resume, purchase_order, bill_of_lading, generic_table), error.request_id (also in the Request-Id header), and no job.

Terminal
$ node parserkit-example.mjs parse invoice-quillfeather-0923.pdf invices
parserkit error 400 INVALID_REQUEST: preset: Invalid option: expected one of "invoice"|"receipt"|"bank_statement"|"resume"|"purchase_order"|"bill_of_lading"|"generic_table" (request_id a56bb5a3c8b3d394, job null)

The program only retries 429 (RATE_LIMITED, BUSY, CONTENT_REFUSALS) and 503 (CONTAINER_UNAVAILABLE). Those answers carry a Retry-After header; the script waits that long and tries again, up to 5 attempts, as long as Retry-After is 60 seconds or less. A longer wait stops it with the error. Every retry reuses the same Idempotency-Key, so the API returns the same job for 24 hours instead of starting a second one, and answers 409 IDEMPOTENCY_CONFLICT if you reuse the key with a different request. See Errors and limits.

Webhook signatures

When you pass webhook_url with the upload, parserkit POSTs events like job.succeeded or job.failed to your HTTPS URL. The receiver reads Parserkit-Signature, which looks like t=<unix seconds>,v1=<hex HMAC-SHA256>, computes the HMAC of "<t>.<raw body>" with your whsec_ signing secret from Webhooks using createHmac, and compares the digests with timingSafeEqual, all on the raw body bytes before parsing JSON. It refuses bodies over 10 MB and timestamps more than 300 seconds off its clock, and if reading a delivery fails it answers 500 and keeps serving. Idempotency-Key holds the event id, the same on all of up to 5 attempts (15 seconds each); in production, store it and skip repeats.

Terminal, the receiver
$ node parserkit-example.mjs serve 8002
listening on port 8002
...
signature ok: job.succeeded job_ygcsdn66uugqna8isima (evt_lcfyuq3noyxfgszobm96, attempt 1)
signature check failed, answered 401

Our receiver ran on port 8002 behind a tunnel. The first request is the real delivery; the second is the same delivery with the first digit of grand_total changed. Lines from earlier local tests are cut at ...

We pointed webhook_url at our receiver through a tunnel during the invoice run. The real delivery, evt_lcfyuq3noyxfgszobm96, got 200. We sent the same delivery again with one digit of an amount changed and got 401, and in a local test a delivery with a timestamp more than 300 seconds old also got 401. Webhooks covers the other headers, such as Parserkit-Attempt, Parserkit-Event and Parserkit-Job-Id.

Questions

What are the file size and page limits?

Up to 25 MB as a multipart upload, or up to 100 MB with file_url or /v1/uploads, and up to 250 pages a job. Results and files are kept 7 days, or 90 days on Pro (see pricing).

Do failed jobs or duplicate uploads cost anything?

No, failed jobs and exact duplicates cost nothing. An exact duplicate (same file, preset and schema) copies the earlier result instead of parsing again.

What do the verification statuses mean?

verified means every required value has a check and none fail, partial means some value has no check, and unverified means there are no checks. discrepancy means a check in verification.checks still fails after repair.

Do I need any npm packages?

No. Node.js 22 has fetch, FormData, Blob, node:crypto and node:http built in.

NextJava

Your first $1 is free, 50 pages with every check and export.