← Course Index

Error Tracking with Sentry

~25 min · Monitoring

Ref
Primary Source
Sentry Docs — Node.js SDK

Official setup guide for Sentry in Node.js including source maps, releases, and user context. Read →

Logging vs Error Tracking

Logs tell you what happened. Error tracking tells you what broke, for which users, how often, with the exact stack trace pointing to the line of code. They complement each other.

Logging (pino)Error tracking (Sentry)
Best forAudit trails, debugging flowsUnhandled exceptions, crash rates
Alert onLog patterns/volumesNew error types, error rate spikes
User contextIf you add it manuallyAutomatic: browser, OS, user ID
Stack traceDepends on implementationAlways, with source map deobfuscation

Sentry Setup

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

// sentry.ts — initialize BEFORE everything else
import * as Sentry from "@sentry/node";
Sentry.init({
  dsn: process.env.SENTRY_DSN,
  environment: process.env.NODE_ENV,
  release: process.env.GIT_SHA,         // Tag errors to specific deploys
  tracesSampleRate: 0.1,
});

// Express: add as FIRST middleware
Sentry.setupExpressErrorHandler(app);

// Add user context after auth middleware
app.use((req, res, next) => {
  if (req.user) Sentry.setUser({ id: req.user.id, email: req.user.email });
  next();
});

// Capture manually with extra context
try {
  await riskyOperation();
} catch (err) {
  Sentry.captureException(err, { extra: { orderId: order.id } });
  res.status(500).json({ error: 'Something went wrong' });
}

Source Maps

# Upload source maps in CI/CD so Sentry shows original code:
- name: Upload Source Maps to Sentry
  env:
    SENTRY_AUTH_TOKEN: FROM_SECRETS
    SENTRY_ORG: your-org
    SENTRY_PROJECT: your-project
  run: |
    npx @sentry/cli releases new GIT_SHA_VAR
    npx @sentry/cli releases files GIT_SHA_VAR upload-sourcemaps ./dist
    npx @sentry/cli releases finalize GIT_SHA_VAR

Alert Rules

In Sentry → Alerts → Create Alert Rule:

💡

Sentry's free tier (5,000 errors/month) covers most side projects. The $26/month Team plan covers 50K events and pays for itself after one production incident caught early.

Check Your Understanding

1. Stack trace shows: "TypeError at app.min.js:1:94812". How do you make it readable?
2. Sentry shows a new error type at 3am affecting 50 users. No one knows. What's missing?
3. What does Sentry.setUser() enable?