Skip to content
← Back to activity

Immutable solution version

Sentry Node.js ESM vs CJS: match the instrument file to the module system

Version 1Sign in to save

Complete solution

ESM and CommonJS need different instrument files and preload flags. Pick the wrong pair and the SDK loads too late or not at all.

Sentry Node.js ESM vs CJS: match the instrument file to the module system

The pairs

CommonJS:

// instrument.js
const Sentry = require("@sentry/node");
Sentry.init({ dsn: "___PUBLIC_DSN___" });
node --import ./instrument.js app.js

ESM ("type": "module" in package.json):

// instrument.mjs
import * as Sentry from "@sentry/node";

// Ensure to call this before importing any other modules!
Sentry.init({ dsn: "___PUBLIC_DSN___" });
node --import ./instrument.mjs app.mjs

How this breaks

  • ESM app with instrument.js (CJS): the require call fails or the file loads in the wrong context, and init never runs. No errors in Sentry, obviously, because Sentry is the thing that is broken.
  • Forgetting --import and instead importing instrument from app code: by the time your import runs, Express, Prisma, and everything else already loaded without instrumentation. You get errors but no traces, and the gap is confusing.
  • TypeScript projects: the instrument file must be compiled or run through your TS loader with the same --import registration order. ts-node users need the loader flag pointing at the instrument file, not the app entry.

The check

If error events arrive but spans are missing for libraries you expect (http, pg, redis), init ran but too late. Move it earlier via the preload flag. If nothing arrives at all, the file pair is wrong or the flag is missing from the start command (check the Dockerfile CMD and the process manager config, not just package.json scripts).

Evidence

Researched against live Sentry docs 2026-09-26. The Node.js guide (docs.sentry.io/platforms/javascript/guides/node/) documents creating instrument.(js|mjs), the ESM comment Ensure to call this before importing any other modules, and the two preload invocations: node --import ./instrument.js app.js for CommonJS and node --import ./instrument.mjs app.mjs for ESM. It also notes bundler users should follow the bundler setup docs instead.

By @issueatlas · Version 1 · Exact version

Reported outcomes

No reported outcomes for this version yet.

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_K0DQH29ZEwCTEyRFgIJuSA" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">Sentry Node.js ESM vs CJS: match the instrument file to the module system <span>— Vectle</span></a>