A green build is not a running function
If sanitize-html 2.17.6 or later makes your Node function fail with ERR_REQUIRE_ESM (or Vercel just says FUNCTION_INVOCATION_FAILED on every request), the cause is that sanitize-html is CommonJS and require()s htmlparser2, and from 2.17.6 it depends on htmlparser2 12, which ships ESM only. The quickest fix that keeps the security patches is an npm override pinning htmlparser2 under sanitize-html back to ^10.1.0, which is still CommonJS. Then add a test that loads the package with --no-experimental-require-module, so the next bump cannot ship the same crash.
That is the whole answer. The rest is how I got there on EduScale, because the order in which things went wrong is the useful part.
The error text
Two different errors, same cause.
In Jest, the first time I bumped the package:
SyntaxError: Cannot use import statement outside a module
In production, after I had "fixed" that and deployed:
500 FUNCTION_INVOCATION_FAILED
And when I finally loaded the deployed bundle locally with require(esm) switched off:
Error [ERR_REQUIRE_ESM]: require() of ES Module .../htmlparser2/...
at .../node_modules/sanitize-html/index.js:1
(Abridged. The part that matters is the second line: the require() is inside sanitize-html, not in my code.)
What broke
EduScale's backend sanitizes forum posts and articles through one small file, Backend/src/utils/sanitize.ts, which wraps sanitize-html with an allow-list. The package had been pinned at 2.17.5. Two advisories landed against it (GHSA-g8qq-57p8-ggw5, GHSA-jxwj-j7wr-gfrw), fixed in 2.17.6 and 2.17.7, so I bumped it (commit 1ffd0197).
Every Jest suite that imported the sanitizer went red with "Cannot use import statement outside a module". The reason is in the package itself. node_modules/sanitize-html/index.js starts with
const htmlparser = require('htmlparser2');
and 2.17.7's package.json says "htmlparser2": "^12.0.0". htmlparser2 11 and up, together with domhandler, domutils, dom-serializer, domelementtype and entities, are ESM only. Jest's CommonJS loader cannot require() an ES module, so it choked.
I did the thing that makes the tests pass. jest.config.cjs got a transform that compiled exactly those six packages to CommonJS for tests, with a transformIgnorePatterns entry that also covered the nested copies under node_modules/sanitize-html/node_modules. The app itself is "type": "module", and on Node 20.19+ and 22.12+ require(esm) is on by default, so I reasoned the real runtime would never hit the error. Locally that held. The gate on the next commit was green: lint, type-check, 599 Jest tests, build. I even pinned engines.node to ^20.19.0 || ^22.12.0 || ^24.0.0 (commit d69882ce) because those are the versions where require(esm) works without a flag.
Then every request to the deployed API returned 500.
Why local passed and production did not
The lockfile diff from the bump is worth reading, because it explains where the ESM copy lived. The top-level node_modules/htmlparser2 stayed at 10.1.0, but marked "dev": true: it was only there for a dev tool. The 12.x tree was installed nested, under node_modules/sanitize-html/node_modules/. So a production install got sanitize-html plus its own private ESM htmlparser2, and nothing else in the tree cared.
Vercel builds the EduScale backend into one function. vercel.json rewrites /(.*) to api/index.ts, and that file ends with
import app from '../dist/main.js';
export default app;
So the entire Express app, every route and every import, loads when the function loads. If anything in that import graph throws, there is no route that can answer. Health check, anonymous reads, everything is the same 500.
I could not read the runtime logs from where I was working, so I reproduced it instead. vercel build locally produces the same api/index.func the platform runs. The last healthy deploy (ac7e7af) and the broken one differed only in the sanitize-html subtree and one unrelated checkout change. Loading the broken function with node --no-experimental-require-module failed at sanitize-html/index.js:1 with ERR_REQUIRE_ESM; loading ac7e7af's function the same way worked. I want to be precise about the evidence: that the Vercel runtime had require(esm) unavailable is inferred from that reproduction, not observed in its logs. It is the only difference that explains the symptom, and the fix built on it made the symptom go away.
The uncomfortable part is that my local gate had tested the wrong thing twice. The Jest transform made the tests pass by changing what the tests loaded. The build passed because bundling an ESM file is not the same as require()-ing it at runtime. Both were green. Neither exercised the artifact that production actually executes. I have written before that a passing test only proves the test passes; this was the same lesson one layer down, at the module loader.
The fix
Commit f339236, four files.
Backend/package.json gets an override so sanitize-html resolves the CommonJS parser:
"overrides": {
"sanitize-html": {
"htmlparser2": "^10.1.0"
}
}
The 2.17.7 code, with both advisory fixes, stays. Only its parser moves back one major. I checked the one behaviour difference I could find: htmlparser2 10 does not decode entities inside <textarea>, so textarea content comes out double-encoded. EduScale's allow-lists in sanitize.ts do not include textarea, so for us it is not reachable. If yours do, test that case before taking this override.
The engines.node pin went back to ">=20"; it existed only for require(esm), and Vercel picks nodejs24.x for either range. jest.config.cjs lost the ESM transform entirely, because with a CommonJS parser there is nothing to transpile.
And the regression test. It does not import the sanitizer into Jest, since that would again test Jest's loader rather than Node's. It spawns a child Node process with require(esm) disabled and asks it to load the real package from disk:
describe('sanitize-html loads without require(esm)', () => {
it('requires cleanly with --no-experimental-require-module', () => {
const run = spawnSync(
process.execPath,
[
'--no-experimental-require-module',
'-e',
"process.stdout.write(require('sanitize-html')('<b>x</b><script>1</script>'))",
],
{ cwd: path.resolve(__dirname, '../../..'), encoding: 'utf8' }
);
expect(run.stderr).not.toMatch(/ERR_REQUIRE_ESM/);
expect(run.status).toBe(0);
expect(run.stdout).toBe('<b>x</b>');
});
});
On the htmlparser2 12 tree, without the override, this test fails with ERR_REQUIRE_ESM. With the override it prints <b>x</b> and exits 0. That is the property it guards. The advisory tests in the same file (Backend/src/tests/utils/sanitize.test.ts) still run the two proof-of-concept payloads with the advisories' own options, and swapping 2.17.5's code back in still fails both, so the override did not quietly reopen the holes it was meant to keep closed.
The last check was the one I had skipped the first time. I served the vercel build output locally on Node 24 against a local Postgres and Redis, and hit real routes: /api/v1/health answered 200 with postgres, redis and queue ok, the anonymous interview-questions and challenges endpoints answered 200, a forum post went in with the script, onclick, onerror and javascript: parts stripped, and checkout with an unknown price id answered 400. Those are local checks of the built function, not production numbers, but they are checks of the artifact that ships.
What to do if you are looking at this error
- Find the
require(). For sanitize-html it is line 1 ofindex.js. For another package, grep its entry file forrequire(of anything that now ships"type": "module". - Read the lockfile diff for added and removed paths, not just version bumps. A nested
node_modules/<pkg>/node_modules/<dep>entry is where the ESM copy hides, and a patch release can introduce it. - If the dependency has a CommonJS major that is still maintained, pin it with
overrides(npm),resolutions(yarn) orpnpm.overrides, scoped to the parent package. Check the changelog between the two majors for a behaviour change that touches your inputs. - Add a test that loads the package in a child process with
--no-experimental-require-module. Do not import it into Jest and call it covered; Jest has its own loader. - After deploying, curl a real route. Deploy status "Ready" means the build and upload finished. It does not mean the function can load.
The title is the lesson. A green build told me the bundler could read the files. Only a request told me the function could run.