Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/getsentry/sentry-javascript/llms.txt

Use this file to discover all available pages before exploring further.

The Sentry Node.js SDK provides comprehensive error monitoring and performance tracking for Node.js applications using OpenTelemetry instrumentation.

Installation

npm install @sentry/node

Basic Setup

Create an instrumentation file and import it before any other code:
// instrument.js
import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  
  // Performance Monitoring
  tracesSampleRate: 1.0,
  
  // Profiling
  profilesSampleRate: 1.0,
});
Import the instrumentation file first in your application:
// app.js
import './instrument.js';
import express from 'express';

const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000);
Or use Node.js --import flag:
node --import ./instrument.js app.js

Express Integration

Automatic instrumentation for Express.js:
import * as Sentry from '@sentry/node';
import express from 'express';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    Sentry.expressIntegration(),
  ],
  tracesSampleRate: 1.0,
});

const app = express();

// Add Sentry error handler - must be before other error handlers
app.use(Sentry.expressErrorHandler());

// Other error handlers
app.use((err, req, res, next) => {
  res.status(500).send('Internal Server Error');
});

app.listen(3000);

Framework Integrations

import * as Sentry from '@sentry/node';
import Fastify from 'fastify';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    Sentry.fastifyIntegration(),
  ],
  tracesSampleRate: 1.0,
});

const fastify = Fastify();

// Add error handler
fastify.setErrorHandler(Sentry.setupFastifyErrorHandler(fastify));

fastify.listen({ port: 3000 });

Database Integrations

import * as Sentry from '@sentry/node';
import { PrismaClient } from '@prisma/client';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    Sentry.prismaIntegration(),
  ],
  tracesSampleRate: 1.0,
});

const prisma = new PrismaClient();

// Database queries are automatically tracked
const users = await prisma.user.findMany();

AI SDK Integrations

import * as Sentry from '@sentry/node';
import OpenAI from 'openai';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    Sentry.openAIIntegration(),
  ],
  tracesSampleRate: 1.0,
});

const client = new OpenAI();

// Automatically tracked
const completion = await client.chat.completions.create({
  model: 'gpt-4',
  messages: [{ role: 'user', content: 'Hello!' }],
});

Performance Monitoring

Automatic Instrumentation

The SDK automatically instruments:
  • HTTP/HTTPS requests
  • Express/Fastify/Koa routes
  • Database queries
  • File system operations
  • Child processes

Custom Spans

import * as Sentry from '@sentry/node';

async function processData() {
  return await Sentry.startSpan(
    {
      name: 'process-data',
      op: 'function',
    },
    async () => {
      // Your code here
      const result = await heavyOperation();
      return result;
    },
  );
}

Nested Spans

import * as Sentry from '@sentry/node';

await Sentry.startSpan(
  { name: 'parent-operation', op: 'task' },
  async () => {
    await Sentry.startSpan(
      { name: 'child-operation-1', op: 'db.query' },
      async () => {
        await db.query('SELECT * FROM users');
      },
    );
    
    await Sentry.startSpan(
      { name: 'child-operation-2', op: 'http.client' },
      async () => {
        await fetch('https://api.example.com/data');
      },
    );
  },
);

Error Handling

Automatic Capture

import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    Sentry.onUncaughtExceptionIntegration(),
    Sentry.onUnhandledRejectionIntegration(),
  ],
});

// Uncaught exceptions are automatically captured
throw new Error('This will be captured');

Manual Capture

import * as Sentry from '@sentry/node';

try {
  riskyOperation();
} catch (error) {
  Sentry.captureException(error, {
    tags: {
      section: 'data-processing',
    },
    extra: {
      operation: 'user-import',
    },
  });
}

Context & Scope

User Context

import * as Sentry from '@sentry/node';

app.use((req, res, next) => {
  if (req.user) {
    Sentry.setUser({
      id: req.user.id,
      email: req.user.email,
      username: req.user.username,
    });
  }
  next();
});

Request Isolation

import * as Sentry from '@sentry/node';

app.get('/user/:id', async (req, res) => {
  // Use isolation scope for request-specific context
  Sentry.withIsolationScope((scope) => {
    scope.setTag('user_id', req.params.id);
    scope.setContext('request', {
      method: req.method,
      url: req.url,
    });
    
    // Process request
  });
});

Profiling

Enable CPU profiling:
import * as Sentry from '@sentry/node';
import { profiler } from '@sentry/node';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  
  integrations: [
    profiler(),
  ],
  
  tracesSampleRate: 1.0,
  profilesSampleRate: 1.0,
});

Cron Monitoring

Monitor scheduled jobs:
import * as Sentry from '@sentry/node';

// Wrap your cron job
await Sentry.withMonitor(
  'my-cron-job',
  async () => {
    // Your cron job logic
    await performScheduledTask();
  },
  {
    schedule: {
      type: 'crontab',
      value: '0 * * * *', // Every hour
    },
    checkinMargin: 5, // minutes
    maxRuntime: 30, // minutes
    timezone: 'America/New_York',
  },
);

Local Variables

Capture local variables in stack traces:
import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    Sentry.localVariablesIntegration(),
  ],
});

Context Lines

Capture source code context:
import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    Sentry.contextLinesIntegration(),
  ],
});

Best Practices

Import First

Always import the instrumentation file before any other code.

Use Integrations

Enable framework-specific integrations for automatic instrumentation.

Request Isolation

Use isolation scopes to separate context between requests.

Sampling

Adjust sample rates in production to control costs.

Configuration

import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  
  // Environment
  environment: 'production',
  release: 'my-app@1.0.0',
  serverName: process.env.HOSTNAME,
  
  // Performance
  tracesSampleRate: 0.2,
  profilesSampleRate: 0.2,
  
  // Integrations
  integrations: [
    Sentry.httpIntegration(),
    Sentry.expressIntegration(),
    Sentry.prismaIntegration(),
    Sentry.contextLinesIntegration(),
    Sentry.localVariablesIntegration(),
  ],
  
  // Error filtering
  ignoreErrors: [
    'ECONNRESET',
    'EPIPE',
  ],
  
  beforeSend(event, hint) {
    // Filter or modify events
    if (event.exception) {
      console.log('Error captured:', hint.originalException);
    }
    return event;
  },
});

Next Steps

Express

Express.js integration guide

Prisma

Prisma integration guide

OpenTelemetry

OpenTelemetry setup

Profiling

CPU profiling guide

Build docs developers (and LLMs) love