Schema Tax

Document Extraction API Node JS Guide for Tax Forms

By Schema TaxPublished Updated

To call a document extraction API from Node JS, use the built-in fetch with FormData to upload the tax PDF, back the file with a disk-based Blob so large scans are not buffered by hand, check the JSON response at runtime as well as in TypeScript, and run long extractions in a background job instead of a request handler.

A note on the samples: they target https://api.example.com, a stand-in host, and they are illustrations rather than a reference. There are no published Schema Tax API docs to quote, so each route, key and JSON layout below was made up for teaching.

Building a document extraction API Node JS client with fetch and FormData

A document extraction API Node JS client no longer needs an HTTP package. Current Node ships fetch, FormData and Blob as globals, so a client is a function that builds a form with the file in it, posts it with an API key header, and checks the status before it reads the body.

The Node.js globals documentation lists fetch and FormData as added in v17.5.0 and v17.6.0, no longer behind the --experimental-fetch flag from v18.0.0, and no longer experimental from v21.0.0. Blob is listed as a global from v18.0.0. On any supported Node release you can drop node-fetch and form-data from new code.

The pieces fit together in a few lines. A FormData holds named parts. A Blob holds the file bytes with a media type. fetch sends the form as a multipart body. Leave Content-Type out of your own headers and let the runtime write it from the form, since the header has to name the boundary string that separates the parts.

// Illustrative client. Placeholder URL; endpoint and fields are examples only.
const BASE_URL = process.env.EXTRACTION_API_URL ?? "https://api.example.com";

function apiKey(): string {
  const key = process.env.EXTRACTION_API_KEY;
  if (!key) throw new Error("EXTRACTION_API_KEY is not set");
  return key;
}

export async function postDocument(file: Blob, filename: string): Promise<unknown> {
  const form = new FormData();
  form.append("file", file, filename);

  const res = await fetch(`${BASE_URL}/v1/extract`, {
    method: "POST",
    headers: { Authorization: `Bearer ${apiKey()}` },
    body: form,
    signal: AbortSignal.timeout(60_000),
  });

  if (!res.ok) {
    const detail = await res.text();
    throw new Error(`extract failed: ${res.status} ${detail.slice(0, 200)}`);
  }
  return res.json(); // unknown until checked; see the typing section
}

Three habits are built into that function. The key comes from the environment and fails loudly when absent. A timeout signal stops a hung request instead of letting it wait forever. And a non-2xx status becomes an error with a short excerpt of the body, which is what you need in a log when a file is rejected.

The return type is unknown on purpose. The body has not been checked yet, and calling it anything more specific would be a promise the code has not kept.

Streaming large tax PDFs from Node JS to an extraction API

Streaming large tax PDFs from Node JS means the process never holds a whole scan in a buffer your code created. The simplest way in current Node is a Blob backed by the file on disk, appended to the same FormData, so your code never calls fs.readFile on the scan.

A scanned tax packet can be large. A color scan of a consolidated brokerage statement at high resolution runs far larger than a digital W-2. Reading it with fs.readFile puts every byte in memory at once, and a worker that uploads several files in parallel multiplies that. On a small container, that is how an upload job runs out of memory in the busiest week of the season.

The Node.js file system documentation for fs.openAsBlob describes a function that returns a Blob whose data is backed by the given file. It was added in v19.8.0 and marked stable in v24.0.0 and v22.17.0. The same page warns that the file must not be modified after the Blob is created, or reads will fail.

// Illustrative: placeholder URL. Upload a large PDF without reading it into a Buffer.
import { openAsBlob } from "node:fs";
import { basename } from "node:path";
import { postDocument } from "./client.js";

export async function uploadFromDisk(path: string) {
  const blob = await openAsBlob(path, { type: "application/pdf" });
  return postDocument(blob, basename(path));
}

That warning shapes the workflow. Write the upload to its final path first, then open it as a Blob, then send it. Do not open a file that another process is still writing, such as a scanner's output folder that fills while you watch it. Copy finished files into a staging folder and upload from there.

Streaming also changes what a timeout means. A large upload on a slow link can spend most of its time sending, before the server has read a page. Size the timeout signal for the slowest connection you expect, or move big files to an API flow that accepts the upload and returns a job ID. The guide to uploading a PDF to an API and getting JSON back covers file size limits, page limits and when an upload returns a job instead of a result.

How should Node JS code type the extraction API response?

Node JS code should type the extraction API response twice: once as a TypeScript type for the editor and compiler, and once as a runtime check that runs on the actual JSON. The type describes what you expect. The check proves the body matches before any amount reaches your database.

The second step is not optional. The TypeScript handbook on everyday types says type assertions are removed by the compiler, that there is no runtime checking associated with them, and that no exception is raised if the assertion is wrong. Writing await res.json() as ExtractResponse tells the compiler a story. It does not inspect the data.

The example below uses a hand-written check with no dependencies, so it runs as-is. A schema library would do the same job with less code. It rejects any amount sent as a bare JSON number, because by the time res.json() returns, a number has already passed through a floating point value.

// Illustrative types and runtime check for an example response shape.
type Field = { value: string | null; flagged: boolean };
type Form = {
  form_type: string;
  tax_year: number;
  page: number;
  fields: Record<string, Field>;
};
export type ExtractResponse = { document_id: string; pages: number; forms: Form[] };

const AMOUNT = /^-?\d+(\.\d{1,2})?$/;

function isField(name: string, f: unknown): f is Field {
  if (typeof f !== "object" || f === null) return false;
  const { value, flagged } = f as Record<string, unknown>;
  if (typeof flagged !== "boolean") return false;
  if (value === null) return true;
  if (typeof value !== "string") return false; // bare numbers rejected
  return name.startsWith("box_") ? AMOUNT.test(value) : true;
}

export function parseExtractResponse(body: unknown): ExtractResponse {
  const b = body as Record<string, unknown>;
  if (typeof b?.document_id !== "string" || !Array.isArray(b.forms))
    throw new Error("response is missing document_id or forms");
  for (const form of b.forms as Record<string, unknown>[]) {
    if (typeof form.form_type !== "string" || !Number.isInteger(form.tax_year))
      throw new Error("form is missing form_type or tax_year");
    for (const [name, f] of Object.entries(form.fields as object))
      if (!isField(name, f)) throw new Error(`field ${name} has an unexpected shape`);
  }
  return body as ExtractResponse;
}

The fictional response this checks is the same shape used in the Python guide: a W-2 for the 2025 tax year with employee_ssn of "XXX-XX-1234", box_1_wages of "52340.17", and box_2_federal_withheld of "6120.40" marked as flagged. A version of that response with "box_1_wages": 52340.17 as a number fails the check, which is the intent.

Keep the check strict and its errors specific. A check that fails with "field box_1_wages has an unexpected shape" points straight at a contract change. One that quietly coerces the value hides it until a total is wrong. For building fictional forms and recorded responses to run this check against, the Python guide's section on testing an extraction API with fictional tax forms carries over to Node with a different test runner.

Where should Node JS extraction calls run: request handler or queue?

Node JS extraction calls should run in a request handler only when the file is small and the API answers well inside the platform's timeout. Multi-page scans, batches and anything a user should not wait on belong in a background job, with a queue between the upload and the call.

Serverless platforms cap how long one invocation can run. The AWS Lambda documentation on function timeouts gives a default of 3 seconds and a maximum of 900 seconds, or 15 minutes, for a standard function. Other platforms set their own limits. Whatever the number, a request handler that uploads a PDF, waits for extraction and then writes to a database spends its whole budget on one file.

The request handler pattern

The handler pattern is fine for one small file at a time: a single-page W-2 uploaded by a user who is watching a spinner. The handler streams the file to the API, checks the response and returns the parsed forms. Set the fetch timeout below the platform's limit so your code, not the platform, decides what the user sees when it runs long.

The queue pattern

The queue pattern splits the work. The handler stores the upload, writes a job record with a status of pending, puts the job ID on a queue and returns at once. A worker takes the job, sends the file, checks the response and updates the record. The user's page polls the record or listens for an update.

That split pays off in three ways. Retries happen in the worker without the user resubmitting. A batch of fifty forms becomes fifty jobs that run at a rate the API allows. And a failure in one file does not fail the others.

Many extraction APIs push the same idea one step further and answer with a job ID of their own, then call a webhook when the result is ready. The worker then only submits, and a separate endpoint receives the result. The guide to async document processing and webhook patterns covers signature checks, retries and duplicate deliveries for that endpoint.

Wherever the call runs, the files it carries are tax documents. Schema Tax masks SSNs and TINs to the last four digits before anything is stored and encrypts files in transit and at rest, as its security section lays out. Your own queue and job records deserve the same care: store a file reference, not the file, and keep identifiers masked in logs.

Node JS extraction mistakes: Number for money and unhandled rejections

The two Node JS extraction mistakes that lose data are reading money into a Number and leaving a promise rejection unhandled. The first changes amounts by fractions of a cent. The second can crash the process in the middle of a batch, abandoning uploads that were already in flight.

Number for money

The MDN reference for the Number type describes a JavaScript Number as a double-precision 64-bit binary IEEE 754 value, so decimal fractions are stored approximately. JSON.parse turns every JSON number into one. Ask for amounts as strings, keep them as strings through validation, and convert them only with a decimal library when you need arithmetic. The comparison of decimal and float for money in JSON has runnable examples of the drift and the fix.

Watch the places a string becomes a number by accident. parseFloat(field.value) in a quick total, a spreadsheet export that writes Number(value), and a database column typed as a floating point all reintroduce the error. A fixed-point decimal column type keeps the value exact at rest.

Unhandled rejections

The Node.js command-line documentation for --unhandled-rejections says the default mode is throw, and that if no unhandledRejection hook is set, the rejection is raised as an uncaught exception. The default changed to throw in v15.0.0. In practice, one forgotten await on a failed upload can end the process.

The usual culprit is a batch loop that starts uploads without awaiting them, or a .then() chain with no .catch(). Use Promise.allSettled for batches, so each file's outcome is recorded and one failure does not take the rest down.

// Illustrative batch: each file succeeds or fails on its own.
import { uploadFromDisk } from "./upload.js";
import { parseExtractResponse } from "./types.js";

export async function uploadBatch(paths: string[]) {
  const results = await Promise.allSettled(
    paths.map(async (p) => parseExtractResponse(await uploadFromDisk(p))),
  );
  return results.map((r, i) => ({
    path: paths[i],
    ok: r.status === "fulfilled",
    error: r.status === "rejected" ? String(r.reason) : undefined,
  }));
}

Promise.allSettled starts every upload at once, which is fine for a handful of files and too many for a season's worth. For larger batches, cap concurrency with a small pool or hand the files to the queue described above.

Flags treated as values

One more slip deserves a mention. A field marked flagged: true is a value the service was not sure about. Code that stores the value and drops the flag turns a question into an answer. Keep the flag in the record and send flagged forms to a person to confirm. More on checking extracted values, and on handling identifiers safely, is in the accuracy and security category.

All posts in Tax Form APIs for Developers