Home / Articles

Node.js passport scans with fetch, idempotency, and a billed flag

Use Node 18 fetch to turn a passport photo into JSON, branch on five scan statuses, and keep idempotency plus a billed flag so a timeout retry is not charged twice.

Publisher: REACTAPP.TOP12 min read2818 words

This article is published in English.

Sources: Passport OCR in Node.js: image to JSON with fetch, idempotency and the billed flag

A passport photo only looks like a one-shot OCR call. In production you still have to decide what a blurry frame means, whether a timed-out POST that you send again was charged twice, and how your own rows record which calls actually cost money.

You can answer those with Node.js 18 or newer and the fetch that ships with it. No SDK. The endpoint belongs to doc.cheap, an API for passports and other identity documents. Treat the vendor-specific defaults with some skepticism. Three habits still apply to any paid HTTP API: send an idempotency key, branch on a stable error code, and keep a per-call flag that says whether that call was billable.

A first call before you sign up

A sandbox credential is printed in the docs: sk_sandbox_public. You can call it with no signup, and the recogniser behind it matches a paid credential. Free usage is 10 recognised documents for a given IP, counted as a lifetime total, plus a hard cap of 10 HTTP calls an hour no matter how they end. Failures burn that hourly budget. The examples below fit inside it. Register later and the account adds a monthly pool of 100 free recognitions, still with no card on file.

The file needs one import from Node's file system module.

import { readFileSync } from "node:fs";

Read specimen.jpg, turn the bytes into base64, and POST them to https://api.doc.cheap/v1/scans. The Authorization header is Bearer sk_sandbox_public, the content type is JSON, and the body is an object whose only field is image. The script then prints meta.status, holder.full_name when a holder exists, and mrz.status.

const image = readFileSync("specimen.jpg").toString("base64");const response = await fetch("https://api.doc.cheap/v1/scans", {
  method: "POST",
  headers: {
    Authorization: "Bearer sk_sandbox_public",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ image }),
});const scan = await response.json();
console.log(scan.meta.status, scan.holder?.full_name, scan.mrz.status);

Name that file first.mjs and start it with node first.mjs. Work finishes inside the request that is already open. You do not receive a job id, you do not poll, and you do not register a webhook. The fields arrive in that same response body.

Do not upload a real passport while you are testing. Issuers commonly post specimen images, and ICAO publishes fake travel documents for a country it calls Utopia, built for this kind of trial.

Resize before you upload. A camera JPEG can weigh several megabytes, and base64 adds roughly another third. Aim for about 1600 pixels on the longer side and a JPEG quality around 85, which is what the docs suggest. A slow first call is often the upload itself: read meta.timing.upload_ms before you decide the API is slow.

The JSON you get back

Successful reads and empty reads share one object. Eight groups are always present: meta, document, holder, fields, mrz, images, quality, and authenticity. Unknown information is null. Keys are not dropped. The sample below is shortened. Its holder comes from a specimen the docs invented, and the fields and images groups are cut down.

{
  "meta": {
    "schema_version": "1.0",
    "id": "01a0af18-cd8d-7a61-9f2d-4c7b8e105da3",
    "status": "recognized",
    "billed": true,
    "confidence": "high",
    "timing": { "upload_ms": 214, "processing_ms": 843, "total_ms": 1074 },
    "created_at": "2026-09-17T09:41:12Z",
    "reference": null
  },
  "document": {
    "kind": "passport", "country": "GRC", "country_name": "Greece",
    "number": "AM7304518", "issue_date": "2022-03-10", "expiry_date": "2032-03-10",
    "is_expired": false, "days_remaining": 2001
  },
  "holder": {
    "given_names": "ELENI SOFIA", "surname": "PARADEIGMA", "full_name": "PARADEIGMA ELENI SOFIA",
    "birth_date": "1994-03-08", "sex": "F", "nationality": "GRC"
  },
  "fields": [],
  "mrz": { "status": "passed", "reason": null, "lines": ["P<GRC…", "AM7304518…"], "text": "P<GRC…" },
  "images": { "document_crop": "data:image/jpeg;base64,…", "main_photo": "data:image/jpeg;base64,…" },
  "quality": { "overall": "pass" },
  "authenticity": { "overall": "not_checked", "checks": [] }
}

What you will actually branch on:

  • Cleaned values sit on document and holder. Dates follow ISO 8601. Countries follow ISO 3166-1 alpha-3. If a scan had nothing for one of those groups, the group itself is null rather than an empty object. That is why the tiny script reaches through holder with ?..
  • Every separate reading lives in fields, and each one carries confidence as high, medium, or low. Expect a band, not a percentage pretending to be exact. A name set in Greek letters is returned as two entries: the Greek form, marked with its language, and a Latin transliteration.
  • mrz.status will be passed, failed, or absent. The zone text is mrz.text, so you can recompute the check digits on your side.
  • authenticity.overall stays not_checked. You are getting text recognition, not a forgery test. Compliance should not hear this described as identity verification.

Unreadable still means HTTP 200

Keep this straight before you write error handling. When the photo cannot be read, the HTTP status is still 200. The outcome is meta.status, and that field has exactly five values. Your next step depends on which one came back.

status                 meaning                                  what to do
recognized             read successfully                        use the data
no_document_found      nothing document-shaped in the frame     ask the user to re-frame
unreadable             a document, but no usable text           better light, focus, angle
unsupported_document   found, but not a type the API knows      stop, a retry reads the same
rejected               failed on the service side               retry once

recognized means the fields are usable. no_document_found means the frame has nothing shaped like a document, so ask for another photo with the page in view. unreadable means a document is visible but the text is not, so change the light, the focus, or the angle. unsupported_document means something was found and this API does not know the type. Posting those same bytes again will not change the outcome, so stop. rejected means the service failed the attempt, and one more try is fair.

Split your branches. HTTP status covers transport problems and API errors. meta.status covers what the scan decided. Throw on no_document_found and you will keep resending a picture that cannot succeed. Persist that outcome as if the document were filled in, and you save an empty record.

What a bad photo costs

meta.billed rides on every response. A live key flips it to true only after the document type is known and extraction actually happened. That bar is a machine-readable zone with valid check digits, five or more fields taken from the printed area, or a barcode that decoded cleanly. You pay nothing when the frame had no document, the image could not be read, the type is unsupported, the service hit an internal error, or the call timed out. How other vendors treat a failed scan, next to this rule, is on the billing comparison.

Sandbox credentials never take money. With sk_sandbox_public, the flag still answers a hypothetical: would a production key have charged for this scan? That is why the flag is worth exercising there. The sandbox credential tied to an account ignores the file you sent. Every reply is one canned specimen, and the flag describes that specimen rather than your upload.

Keep the flag next to the result. It belongs to a single call. On a live key, total the stored rows where the flag is true across one UTC calendar month. GET /v1/usage reports that same total as scans.billed for the month. No second reconciliation job is required.

A timeout must not bill twice

The retry you should fear follows a timeout. Maybe the first POST landed. Maybe it did not. You cannot tell. Add the header Idempotency-Key when you call POST /v1/scans. The value may be from 1 character long up to 255. On a live key, repeating that key with an identical body replays the stored result and drops the image crops. Recognition does not run again, and the call is not charged again.

Three constraints from the reference should shape the client:

  • The key is stored with a fingerprint of every byte in the body. Keep the key, change the image, and you receive HTTP 409 plus idempotency_conflict. Nothing is replayed in silence.
  • A key lasts while its result is stored. Set retain_hours to 0 and nothing is kept, yet the key stays remembered for a day. Retry during that day and the response is HTTP 409 with idempotency_replay_unavailable. The scan does not execute a second time, and no payload is available to return. After the day ends, that key is free and the next call is a fresh scan. Pick one behavior per workflow. Either you keep the result so a retry can replay it, or you keep nothing and lose replay.
  • Sandbox mode accepts the header and then ignores it, since those calls are never charged. Sending the header anyway still lets you exercise the branch.

The client you would actually run

Put this version in a service. One UUID is created per image and reused for every retry of that image. Only codes the docs call retryable are retried. A Retry-After hint is followed when it asks for a minute or less. A longer hint is a failure, not a nap inside the call. scan hands back the full payload so no field is dropped.

The file is scan.mjs. It pulls async file reads and a UUID helper from Node.

// scan.mjs
import { readFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";

DOC_CHEAP_API_KEY overrides the key, and the fallback is still sk_sandbox_public. The retry set is rate_limited, document_repeated, internal_error, engine_unavailable, service_unavailable, maintenance, and idempotency_in_progress. ScanError keeps the HTTP status, error.code, docs_url, and request_id. scan reads the file, base64-encodes it, and sends image, an optional reference, and options.return_portrait set to false. The default is 4 attempts. One randomUUID() is created for that image and sent on every try as Idempotency-Key. The fetch aborts after 60 seconds. A network failure, or a body that is not JSON (a proxy can answer with HTML), sleeps 1000 * 2 ** attempt and tries again until the attempts run out. A successful HTTP response returns the payload untouched. For a retryable error, Retry-After is used when it is a positive number, otherwise the wait is 2 ** attempt seconds. If that wait is over 60 seconds the call throws. The sandbox hourly limit can ask you to wait up to an hour, and sleeping that long inside one invocation helps nobody. summarise is only for the demo printer: if meta.status is not recognized it returns ok: false plus the status and billed; otherwise it flattens the fields you usually want. Running the file as a script calls scan on process.argv[2] with reference set to demo-1, prints the summary and meta.timing, and on ScanError logs the message, the docs URL, and the request id before exiting 1.

const API = "https://api.doc.cheap/v1/scans";
const KEY = process.env.DOC_CHEAP_API_KEY ?? "sk_sandbox_public";
const RETRY = new Set([
  "rate_limited", "document_repeated", "internal_error", "engine_unavailable",
  "service_unavailable", "maintenance", "idempotency_in_progress",
]);export class ScanError extends Error {
  constructor(status, error) {
    super(`${error.code} (${status}): ${error.message}`);
    this.code = error.code;
    this.docsUrl = error.docs_url;
    this.requestId = error.request_id;
  }
}const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));export async function scan(path, { reference = null, attempts = 4 } = {}) {
  const image = (await readFile(path)).toString("base64");
  const body = JSON.stringify({ image, reference, options: { return_portrait: false } });
  const idempotencyKey = randomUUID(); // one key for this image, reused on every retry  for (let attempt = 1; ; attempt++) {
    let response;
    try {
      response = await fetch(API, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${KEY}`,
          "Content-Type": "application/json",
          "Idempotency-Key": idempotencyKey,
        },
        body,
        signal: AbortSignal.timeout(60_000),
      });
    } catch (networkError) {
      if (attempt >= attempts) throw networkError;
      await sleep(1000 * 2 ** attempt);
      continue;
    }    // A proxy in the way can answer with HTML; treat that like a network error.
    const payload = await response.json().catch(() => null);
    if (payload === null) {
      if (attempt >= attempts) throw new Error(`HTTP ${response.status} without a JSON body`);
      await sleep(1000 * 2 ** attempt);
      continue;
    }
    if (response.ok) return payload;    const { error } = payload;
    if (!RETRY.has(error.code) || attempt >= attempts) throw new ScanError(response.status, error);
    // The sandbox's hourly limit asks for up to an hour; waiting that long
    // inside one call helps nobody, so anything over a minute is an error.
    const retryAfter = Number(response.headers.get("Retry-After"));
    const wait = retryAfter > 0 ? retryAfter : 2 ** attempt;
    if (wait > 60) throw new ScanError(response.status, error);
    await sleep(1000 * wait);
  }
}export function summarise({ meta, document, holder, mrz }) {
  if (meta.status !== "recognized") {
    return { ok: false, status: meta.status, billed: meta.billed };
  }
  return {
    ok: true,
    billed: meta.billed,
    confidence: meta.confidence,
    kind: document?.kind ?? null,
    country: document?.country ?? null,
    number: document?.number ?? null,
    expiryDate: document?.expiry_date ?? null,
    isExpired: document?.is_expired ?? null,
    surname: holder?.surname ?? null,
    givenNames: holder?.given_names ?? null,
    birthDate: holder?.birth_date ?? null,
    mrz: mrz.status,
    mrzReason: mrz.reason,
  };
}if (import.meta.url === `file://${process.argv[1]}`) {
  try {
    const result = await scan(process.argv[2], { reference: "demo-1" });
    console.log(summarise(result), result.meta.timing);
  } catch (err) {
    if (err instanceof ScanError) console.error(err.message, err.docsUrl, err.requestId);
    else throw err;
    process.exitCode = 1;
  }
}

Invoke it as node scan.mjs specimen.jpg. On 24 September 2026 the public sandbox printed the object below for a generated test passport. Document fields in that printout are shown as .... The rest matches the terminal exactly.

{
  ok: true,
  billed: true,
  confidence: 'medium',
  kind: 'passport',
  country: '…',
  number: '…',
  expiryDate: '…',
  isExpired: false,
  surname: '…',
  givenNames: '…',
  birthDate: '…',
  mrz: 'passed',
  mrzReason: null
} { upload_ms: 271, processing_ms: 410, total_ms: 691 }

Seeing billed set to true under a sandbox credential does not mean money moved. It means a production key would have charged for that scan.

A few decisions in that file are easy to miss:

  • Network failure is the only time fetch rejects the promise. An HTTP 4xx or 5xx still resolves, so the code looks at response.ok and parses a JSON error either way.
  • Switch on error.code, not on the status number by itself. For POST /v1/scans, one 409 covers three idempotency failures, and one 503 covers three separate outages. Each wants its own recovery. The error JSON always includes a code, a message, a docs_url, a request_id, and an event_id. Write request_id to your logs. Support will ask for it. The codes are listed in the error catalog.
  • Another loop will not fix a validation_failed body, a payload_too_large body, an unauthorized key, or insufficient_credits. Change the request or the account. After the free allowance is gone, the sandbox answers with registration_required, and waiting does not put those free reads back. document_repeated shows up when one image is posted too often inside an hour. The client does retry that code, but it refuses to sleep past 60 seconds.
  • Keep the request body out of logs. Those bytes are an identity document.
  • A reference you send is copied onto meta.reference. Cap it at 128 characters. It is the straightforward link from a scan to an order or a user on your side. Front and back of one card are separate calls, and they should carry the same reference.

How long results stay

While the request is in flight, the upload lives in memory and is not persisted to disk or object storage. The JSON result is stored separately, and you load it later with GET /v1/scans/{id}. How long it remains is your choice. Account settings allow a 24-hour window, a 7-day window, a 30-day window, or a one-year window. A brand-new account starts on the one-year setting. On one call, options.retain_hours takes any integer from 0 through 8760. Zero means the service writes no row. If the caller consumes the JSON immediately and will never fetch it again, pass 0, and accept that a retry during the next day cannot return a body that was never stored.

The client sets return_portrait to false, which omits images.main_photo. That field would have been the cropped portrait. Leaving it out is one less sensitive image in your logs and in your own storage. The full-page crop is still in the payload.

A live key

Put your own credential in DOC_CHEAP_API_KEY and drop the sk_sandbox_public fallback. The URL does not change, and neither does the JSON shape. A registered credential may send 60 requests each minute. That account's monthly free pool is 100 recognitions. Extra credits are purchased in cryptocurrency. The smallest top-up is $1. Card checkout is not offered, so say so before you demo this to a finance team.

If a field in the JSON is painful to consume from Node, email admin at doc.cheap. Shape complaints are what that mailbox is for.

The sample above came from a run on the live sandbox, pasted the way the terminal printed it.