POSTMORTEM

Four pdf.js problems behind one 502 on Netlify

JUNE 11, 2026 · 6 MIN · READYSETBIND
TL;DR

A PDF route that passed typecheck and local runs failed on Netlify for four separate reasons, and each one returned the same 502.

  • A ReadySetBind route that places signature fields on a PDF worked locally and returned a generic 502 error on Netlify.
  • Four pdf.js problems caused it, each hidden until the one before it was fixed, and the last fix merged about 22.5 hours after the route.
  • The fixes are written up in a doc and in code comments, but no test or CI step guards them, so confirming the worker file shipped is a manual check.

ReadySetBind has a route that reads a quote PDF and works out where each signature field belongs on the page. It is a Next.js API route (a server function behind one URL, in the React framework the app is built on). Claude finds text anchors in the document (the words that mark where a field goes), and the route turns them into page coordinates with pdfjs-dist, the npm package for Mozilla's pdf.js engine. The route passed typecheck and worked in local runs. On Netlify it returned a 502 (the generic error a server sends when the code behind it fails), and the commit for the last fix records a real placement with all 18 of its fields stuck waiting for someone to place them by hand. After the fixes, the project's solution doc records 12 of 18 fields placing themselves, with the other six (the checkbox and radio-button fields plus one ambiguous signature) going to a person by design.

The route merged on the afternoon of June 3, 2026. The first fix merged that evening, the other three merged within 57 minutes of each other on June 4, and the last landed at 14:03, about 22.5 hours after the route. Netlify runs the route as a serverless function (a short-lived process on Netlify's machines rather than a server I manage), and pdf.js hit four separate problems there.

The four failures, in the order they surfaced

Each failure stayed hidden until the one in front of it was fixed, all four returned the same 502, and leaving out any one fix brings that 502 back.

  1. The worker path, plus a time limit. pdf.js 4 ships as ESM (the modern JavaScript module format) and rejected the bare filesystem path I gave it for its worker (the separate script pdf.js uses to parse documents), throwing Received protocol 'c:'. The try/catch around it guarded require.resolve(), which succeeded, while the real error came later inside getDocument, so the fallback never ran. The fix switched to the legacy build (the pdf.js build for older JavaScript environments) and stopped setting workerSrc (the option that tells pdf.js where its worker lives). The same fix also kept the route under Netlify's roughly ten-second function limit by extracting only the four or so pages it needs: a several-hundred-page package had taken about 12 seconds, and a 124-page package now took 0.7. This fix was verified locally against the example PDFs, and the next three failures happen only on Netlify.
  2. Fonts that loaded locally and not on Netlify. useSystemFonts: true loads fonts through @napi-rs/canvas, a native module (a compiled add-on built for one operating system) that is missing from Netlify's runtime. The route crashed at about 3.8 seconds, so this was never a timeout. The fix set useSystemFonts: false and disableFontFace: true, which turn off font handling the route does not need, because field positions come from the PDF's content stream (the drawing instructions inside the file).
  3. A bundler that broke the library's own import. Next.js packed pdfjs-dist into a webpack chunk (webpack is the bundler Next.js uses, and a chunk is one file built from many modules). That broke the library's internal dynamic import() of its worker (an import whose path is worked out at run time) and produced Cannot find module /var/task/.next/server/chunks/pdf.worker.mjs. The fix was serverExternalPackages: ["pdfjs-dist"], which tells Next.js to leave the package out of the bundle.
  4. A deploy without the worker file. Next's file tracer, @vercel/nft (the tool that decides which files are uploaded with each function), follows direct imports but not a dependency's internal dynamic import, so the 2.3 MB worker never reached Netlify. The fix added an outputFileTracingIncludes entry (the setting that names extra files the tracer must ship) for the route, shown below.
next.config.ts · the include that was missing for the anchor route
BEFORE// no outputFileTracingIncludes entry for this route
FIX"/api/placements/*/resolve-anchors": ["./node_modules/pdfjs-dist/legacy/build/pdf.worker.mjs"]

the keyNext.js names the route's id folder [id], and that bracket form also matched when it was tested. The * wildcard went in with the fix so the match does not depend on that.

How the last three failures were diagnosed

The last three came out of the Netlify function logs and the app's 502 telemetry (the error record the app writes when the route fails). That telemetry had recorded only error_class=Error, the generic class name, so the commit that fixed the font problem extended it to carry the pdf.js error message, scrubbed of personal data, and the first stack frame (the line of code where the error was thrown). In that commit's words, "the bare error_class=Error is what made this hard to pin down."

What was written down afterwards, and what is still manual

All four fixes are written up in a solution doc in the project's docs/solutions folder, updated on June 8 with the last three, and next.config.ts carries explanatory comments. The richer telemetry is the only change to the running system, and it helps with diagnosis without preventing a repeat. No test, CI step (an automated check that runs on each pull request) or lint rule checks the config or the build's trace file (the .nft.json list of files the tracer decided to ship).

Here are the five settings and the trace check. They are simplified and are not the product's code. This is what worked for a Next.js app on Netlify with pdfjs-dist 4, so check the trace file on your own host. The page-extraction step from the first fix is left out, because which pages to keep depends on your documents.

// next.config.mjs
const nextConfig = {
  // Keep pdf.js out of the webpack bundle.
  serverExternalPackages: ["pdfjs-dist"],
  outputFileTracingIncludes: {
    // Replace with your route's path; use * for a dynamic segment.
    "/api/documents/*/extract": [
      "./node_modules/pdfjs-dist/legacy/build/pdf.worker.mjs",
    ],
  },
};

export default nextConfig;

Use this when a server route imports pdfjs-dist and the host uploads only the files the tracer lists.

// Server-side PDF loading
import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs";

// No GlobalWorkerOptions.workerSrc is set anywhere.
/** @param {Uint8Array} data the PDF file's bytes */
export async function loadPdf(data) {
  return getDocument({
    data,
    useSystemFonts: false,
    disableFontFace: true,
  }).promise;
}

Use this when you need text positions from a PDF on the server and never render the pages.

// check-trace.mjs, run after `next build`
import { readFileSync } from "node:fs";

const trace = process.argv[2]; // the route's route.js.nft.json
const { files } = JSON.parse(readFileSync(trace, "utf8"));

if (!files.some((f) => f.endsWith("pdf.worker.mjs"))) {
  console.error(`pdf.worker.mjs is missing from ${trace}`);
  process.exit(1);
}
console.log("pdf.worker.mjs is in the trace");

Pass it the route's route.js.nft.json from under .next/server/app/, and it exits with an error when the worker is missing, which is the fourth failure. In ReadySetBind this check is a manual step.

Trust belongs in the schema, not the application.
The operating principle behind every project here. A rule the database enforces can't be forgotten in a hurry. Constraints, denied-by-default access, append-only logs — the controls that hold are the ones the system won't run without.