ESM (MJS)

Learn about running Sentry in an ESM application.

When running your application in ESM mode, you can't use require() to load modules. Instead, you have to use the --import command line options to load a module before the application starts.

You need to create a file named instrument.mjs that imports and initializes Sentry:

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

// Ensure to call this before importing any other modules!
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

  // Add Tracing by setting tracesSampleRate
  // We recommend adjusting this value in production
  tracesSampleRate: 1.0,
});

Adjust the Node.js call for your application to use the --import parameter and point it at instrument.js, which contains your Sentry.init() code:

Copied
# Note: This is only available for Node v18.19.0 onwards.
node --import ./instrument.mjs app.mjs

If it is not possible for you to pass the --import flag to the Node.js binary, you can alternatively use the NODE_OPTIONS environment variable as follows:

Copied
NODE_OPTIONS="--import ./instrument.mjs" npm run start

We do not support ESM in Node versions before 18.19.0.

By default, all packages are wrapped under the hood by import-in-the-middle. If you run into a problem with a package, you can skip instrumentation for it by configuring registerEsmLoaderHooks in your Sentry.init() config:

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

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  registerEsmLoaderHooks: {
    // Provide a list of package names to exclude from instrumentation
    exclude: ["package-name"],
  },
});
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").