@@ -21,6 +21,11 @@ yarn add @sentry/node
21
21
22
22
## Usage
23
23
24
+ Sentry should be initialized as early in your app as possible. It is essential that you call ` Sentry.init ` before you
25
+ require any other modules in your application, otherwise auto-instrumentation of these modules will ** not** work.
26
+
27
+ You need to create a file named ` instrument.js ` that imports and initializes Sentry:
28
+
24
29
``` js
25
30
// CJS Syntax
26
31
const Sentry = require (' @sentry/node' );
@@ -33,26 +38,39 @@ Sentry.init({
33
38
});
34
39
```
35
40
36
- Note that it is necessary to initialize Sentry ** before you import any package that may be instrumented by us** .
41
+ You need to require or import the ` instrument.js ` file before importing any other modules in your application. This is
42
+ necessary to ensure that Sentry can automatically instrument all modules in your application:
43
+
44
+ ``` js
45
+ // Import this first!
46
+ import ' ./instrument' ;
47
+
48
+ // Now import other modules
49
+ import http from ' http' ;
37
50
38
- [ More information on how to set up Sentry for Node in v8.] ( https://github.com/getsentry/sentry-javascript/blob/develop/docs/v8-node.md )
51
+ // Your application code goes here
52
+ ```
39
53
40
54
### ESM Support
41
55
42
- Due to the way OpenTelemetry handles instrumentation, this only works out of the box for CommonJS (` require ` )
43
- applications.
56
+ When running your application in ESM mode, you should use the Node.js
57
+ [ ` --import ` ] ( https://nodejs.org/api/cli.html#--importmodule ) command line option to ensure that Sentry is loaded before
58
+ the application code is evaluated.
44
59
45
- There is experimental support for running OpenTelemetry with ESM (` "type": "module" ` ):
60
+ Adjust the Node.js call for your application to use the ` --import ` parameter and point it at ` instrument.js ` , which
61
+ contains your ` Sentry.init ` () code:
46
62
47
63
``` bash
48
- node --experimental-loader=@opentelemetry/instrumentation/hook.mjs ./app.js
64
+ # Note: This is only available for Node v18.19.0 onwards.
65
+ node --import ./instrument.mjs app.mjs
49
66
```
50
67
51
- You'll need to install ` @opentelemetry/instrumentation ` in your app to ensure this works.
68
+ If it is not possible for you to pass the ` --import ` flag to the Node.js binary, you can alternatively use the
69
+ ` NODE_OPTIONS ` environment variable as follows:
52
70
53
- See
54
- [ OpenTelemetry Instrumentation Docs ] ( https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation#instrumentation-for-es-modules-in-nodejs-experimental )
55
- for details on this - but note that this is a) experimental, and b) does not work with all integrations.
71
+ ``` bash
72
+ NODE_OPTIONS= " --import ./instrument.mjs " npm run start
73
+ ```
56
74
57
75
## Links
58
76
0 commit comments