Node.js

Learn how to manually set up Sentry in your Node.js app and capture your first errors.

AI Rules for Cursor or Windsurf

Sentry provides a set of rules you can use to help your LLM use Sentry correctly. Copy this file and add it to your projects rules configuration.

rules.md
Copied
These examples should be used as guidance when configuring Sentry functionlaity within a project.

# Error / Exception Tracking

- Use `Sentry.captureException(error)` to capture an exception and log the error in Sentry.
- Use this in try catch blocks or areas where exceptions are expected

# Logs

- Where logs are used, ensure they are imported using `import * as Sentry from "@sentry/node"`
- Reference the logger using `const { logger } = Sentry`
- Sentry initialization needs to be updated to include the `logger` integration.
- Sentry offers a consoleLoggingIntegration that can be used to log specific console error types automatically without instrumenting the individual logger calls

## Configuration

- In Node.js the Sentry initialization is typically in `instrumentation.ts`

### Baseline

```javascript
import * as Sentry from "@sentry/node";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

  _experiments: {
    enableLogs: true,
  },
});
```

### Logger Integration

```javascript
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    // send console.log, console.error, and console.warn calls as logs to Sentry
    Sentry.consoleLoggingIntegration({ levels: ["log", "error", "warn"] }),
  ],
});
```

## Logger Examples

```javascript
logger.trace("Starting database connection", { database: "users" });
logger.debug("Cache miss for user", { userId: 123 });
logger.info("Updated profile", { profileId: 345 });
logger.warn("Rate limit reached for endpoint", {
  endpoint: "/api/results/",
  isEnterprise: false,
});
logger.error("Failed to process payment", {
  orderId: "order_123",
  amount: 99.99,
});
logger.fatal("Database connection pool exhausted", {
  database: "users",
  activeConnections: 100,
});
```

# Tracing Examples

- Spans should be created for meaningful actions within an applications like button clicks, API calls, and function calls
- Ensure you are creating custom spans with meaningful names and operations
- Use the `Sentry.startSpan` function to create a span
- Child spans can exist within a parent span

## Custom Span instrumentation in component actions

```javascript
function TestComponent() {
  const handleTestButtonClick = () => {
    // Create a transaction/span to measure performance
    Sentry.startSpan(
      {
        op: "ui.click",
        name: "Test Button Click",
      },
      async (span) => {
        const value = "some config";
        const metric = "some metric";

        // Metrics can be added to the span
        span.setAttribute("config", value);
        span.setAttribute("metric", metric);

        doSomething();
      },
    );
  };

  return (
    <button type="button" onClick={handleTestButtonClick}>
      Test Sentry
    </button>
  );
}
```

## Custom span instrumentation in API calls

```javascript
async function fetchUserData(userId) {
  return Sentry.startSpan(
    {
      op: "http.client",
      name: `GET /api/users/${userId}`,
    },
    async () => {
      try {
        const response = await fetch(`/api/users/${userId}`);
        const data = await response.json();
        return data;
      } catch (error) {
        // Capture error with the current span
        Sentry.captureException(error);
        throw error;
      }
    },
  );
}
```

You need:

Choose the features you want to configure, and this guide will show you how:

Want to learn more about these features?
  • Issues (always enabled): Sentry's core error monitoring product that automatically reports errors, uncaught exceptions, and unhandled rejections. If you have something that looks like an exception, Sentry can capture it.
  • Tracing: Track software performance while seeing the impact of errors across multiple systems. For example, distributed tracing allows you to follow a request from the frontend to the backend and back.
  • Profiling: Gain deeper insight than traditional tracing without custom instrumentation, letting you discover slow-to-execute or resource-intensive functions in your app.

Run the command for your preferred package manager to add the Sentry SDK to your application:

Copied
npm install @sentry/node @sentry/profiling-node --save

To import and initialize Sentry, create a file named instrument.(js|mjs) in the root directory of your project and add the following code:

instrument.js
Copied
const Sentry = require("@sentry/node");
//  profiling
const { nodeProfilingIntegration } = require("@sentry/profiling-node");
//  profiling

// Ensure to call this before requiring any other modules!
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

  // Adds request headers and IP for users, for more info visit:
  // https://docs.sentry.io/platforms/javascript/guides/node/configuration/options/#sendDefaultPii
  sendDefaultPii: true,
  //  profiling

  integrations: [
    // Add our Profiling integration
    nodeProfilingIntegration(),
  ],
  //  profiling
  //  performance

  // Set tracesSampleRate to 1.0 to capture 100%
  // of transactions for tracing.
  // We recommend adjusting this value in production
  // Learn more at
  // https://docs.sentry.io/platforms/javascript/guides/node/configuration/options/#tracesSampleRate
  tracesSampleRate: 1.0,
  //  performance
  //  profiling

  // Set profilesSampleRate to 1.0 to profile 100%
  // of sampled transactions.
  // This is relative to tracesSampleRate
  // Learn more at
  // https://docs.sentry.io/platforms/javascript/guides/node/configuration/options/#profilesSampleRate
  profilesSampleRate: 1.0,
  //  profiling
});

Make sure to initialize Sentry before you require or import any other modules in your app. Otherwise, auto-instrumentation won't work for these modules.

Require the instrument.js file before any other modules:

app.js
Copied
// Require this first!
require("./instrument");

// Now require other modules
const http = require("http");

// Your application code goes here

When running your application in ESM mode, use the --import command line option and point it to instrument.mjs to load the module before the application starts:

Copied
# Note: This is only available for Node v18.19.0 onwards.
node --import ./instrument.mjs app.mjs

The stack traces in your Sentry errors probably won't look like your actual code. To fix this, upload your source maps to Sentry. The easiest way to do this is by using the Sentry Wizard:

Copied
npx @sentry/wizard@latest -i sourcemaps

Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.

First, let's verify that Sentry captures errors and creates issues in your Sentry project. Add the following code snippet to your main application file, which will call an undefined function, triggering an error that Sentry will capture:

Copied
setTimeout(() => {
  try {
    foo();
  } catch (e) {
    Sentry.captureException(e);
  }
}, 99);

To test your tracing configuration, update the previous code snippet by starting a performance trace to measure the time it takes for the execution of your code:

Copied
Sentry.startSpan(
  {
    op: "test",
    name: "My First Test Transaction",
  },
  () => {
    setTimeout(() => {
      try {
        foo();
      } catch (e) {
        Sentry.captureException(e);
      }
    }, 99);
  },
);

Now, head over to your project on Sentry.io to view the collected data (it takes a couple of moments for the data to appear).

Need help locating the captured errors in your Sentry project?
  1. Open the Issues page and select an error from the issues list to view the full details and context of this error. For an interactive UI walkthrough, click here.
  2. Open the Traces page and select a trace to reveal more information about each span, its duration, and any errors. For an interactive UI walkthrough, click here.
  3. Open the Profiles page, select a transaction, and then a profile ID to view its flame graph. For more information, click here.

At this point, you should have integrated Sentry into your Node.js application and should already be sending data to your Sentry project.

Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are:

Are you having problems setting up the SDK?
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").