ESM (MJS)
Learn about running Sentry in an ESM application.
Are you unsure if you should use this installation method? Review our installation methods.
When running your application in ECMAScript Modules (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.
Step 1: Create a file named instrument.mjs
that imports and initializes Sentry:
instrument.mjs
import * as Sentry from "@sentry/nestjs";
// 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,
});
Step 2: Adjust your application's start command to use the --import parameter:
# Note: This is only available for Node v18.19.0 onwards.
"start": "--import ./instrument.mjs nest start"
If you can't pass the --import
flag to the Node.js binary, you can alternatively use the NODE_OPTIONS
environment variable as follows:
NODE_OPTIONS="--import ./instrument.mjs" npm run start
By default, all packages are automatically wrapped by import-in-the-middle to aid instrumenting them.
If import-in-the-middle
encounters problems wrapping a package, you may see syntax errors at runtime or logged errors in your console:
SyntaxError: The requested module '...' does not provide an export named '...'
(node:3368) Error: 'import-in-the-middle' failed to wrap 'file://../../path/to/file.js'
To confirm that these errors are caused by import-in-the-middle
, disable it by setting registerEsmLoaderHooks
to false. Note, this will also disable tracing instrumentation:
instrument.mjs
import * as Sentry from "@sentry/nestjs";
Sentry.init({
registerEsmLoaderHooks: false,
});
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").