Late Initialization for Node.js

Learn about running Sentry in an ESM or CJS application, in scenarios where you cannot run init early.

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:

Copied
node --import @sentry/node/import main.mjs

This works for CommonJS applications as well. --require is no longer supported, so use --import there too:

Copied
node --import @sentry/node/import app.js

With the flag in place, call Sentry.init() at the point of your choosing:

main.mjs
Copied
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

--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.

Was this helpful?
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").