Late Initialization for Node.js
Learn about running Sentry in an ESM or CJS application, in scenarios where you cannot run init early.
Are you unsure if you should use this installation method? Review our installation methods.
For auto-instrumentation to work, Sentry.init() normally has to run before anything else is imported in your application.
In some cases that isn't possible, for example when you fetch your DSN from an external source. For these cases, --import the SDK itself instead of your own instrument file. The SDK then wraps the modules your application imports, and you call Sentry.init() later:
node --import @sentry/node/import main.mjs
node --import @sentry/node/import main.mjs
This works for CommonJS applications as well. --require is no longer supported, so use --import there too:
node --import @sentry/node/import app.js
node --import @sentry/node/import app.js
With the flag in place, call Sentry.init() at the point of your choosing:
main.mjsimport * as Sentry from "@sentry/node";
import startApp from "./app.mjs";
import fetchDsn from "./utils/fetchDsn.mjs";
startApp();
const dsn = await fetchDsn();
Sentry.init({
dsn,
// Add Tracing by setting tracesSampleRate
// We recommend adjusting this value in production
tracesSampleRate: 1.0,
});
// From now on, Sentry is initialized,
// and the app is still auto-instrumented
import * as Sentry from "@sentry/node";
import startApp from "./app.mjs";
import fetchDsn from "./utils/fetchDsn.mjs";
startApp();
const dsn = await fetchDsn();
Sentry.init({
dsn,
// Add Tracing by setting tracesSampleRate
// We recommend adjusting this value in production
tracesSampleRate: 1.0,
});
// From now on, Sentry is initialized,
// and the app is still auto-instrumented
Use this method only if it's strictly necessary. Anything that happens before Sentry.init() runs isn't captured, so an error thrown during startup goes unreported. In most cases it's better to find a way to run Sentry.init() early, as described in the quickstart.
--import @sentry/node/import wraps the modules your application imports before your code runs. At that point the modules are wrapped but inactive: nothing is emitted or captured from them.
Once you call Sentry.init(), the wrapped modules start emitting data to Sentry.
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").