Skip to main content

Use the Node.js agent with ESM

The Contrast Node.js agent provides full support for using ECMAScript modules (ESM) in Node.js server-side applications. ESM is the official standard format to package JavaScript client-side code.

There are two ways to run the Contrast Node.js agent if you are using ESM server-side applications.

  • To explicitly assert that the code you're running is ESM and should be run as such, use the MJS file extension. Learn more about determining a module system wiith file extensions in the Node.js documentation.

    When you use an MJS extension, Node.js knows that you've written ESM and will parse your JavaScript as such. The same is true for CJS; Node.js knows that a CJS file extension should run as CommonJS, and will parse your JavaScript as CommonJS.

  • Otherwise, you can get your Node.js applications to run as ESM rather than CommonJS by including "type": "module" in your package.json, like this:

    "main": "index.js", 
    "type": "module",

    This specifically tells Node.js to parse your JS files under this package.json as ESM. Otherwise, by default (or when you use "type": "commonjs"), Node.js will parse your JS files as CommonJS.

When instrumenting an application that uses ESM (or a combination of both ESM and CJS), the way to start the application with the agent depends on the Node.js engine version and if your application is using ESM code or modules.

  • For Node LTS versions greater than or equal to 18.19.0

    Use --import to start the application:

    node --import @contrast/agent app-main.mjs [app arguments]
  • For Node LTS versions greater than or equal to 16.17.0 and less than 18.19.0.

    Use --loader to start the application:

    node --loader @contrast/agent app-main.mjs [app arguments]
  • For Node LTS versions less than 16.17.0. This is also applicable to applications not using the ESM syntax.

    Use the legacy method for starting the application:

    node -r @contrast/agent app-main.js [app arguments]