All posts

Node.js Debugging Tips and Techniques

Master Node.js debugging with the built-in inspector, async stack traces, memory leak detection, and production debugging strategies.

Node.js Debugging Tips and Techniques

Beyond console.log, Node.js offers powerful debugging tools. Here's how to use them effectively.

Built-in Debugger

Start Node.js with the inspector:

# Start with inspector
node --inspect server.js

# Break on first line
node --inspect-brk server.js

Connect via Chrome DevTools at chrome://inspect or use VS Code's built-in debugger with this launch config:

{
  "type": "node",
  "request": "launch",
  "name": "Debug Server",
  "program": "${workspaceFolder}/server.js",
  "console": "integratedTerminal"
}

Async Stack Traces

Enable long stack traces in Node.js 16+:

node --enable-source-maps --async-stack-traces server.js

This shows the full async call chain instead of truncated traces.

Debug Memory Leaks

// Take heap snapshots
const v8 = require('v8');
const fs = require('fs');

function writeHeapSnapshot() {
  const filename = v8.writeHeapSnapshot();
  console.log(`Heap snapshot written to ${filename}`);
}

// Monitor memory growth
setInterval(() => {
  const usage = process.memoryUsage();
  console.log(`RSS: ${Math.round(usage.rss / 1024 / 1024)}MB`);
  console.log(`Heap: ${Math.round(usage.heapUsed / 1024 / 1024)}MB`);
}, 30000);

Common leak sources:

  • Event listeners not removed — use emitter.listenerCount() to check
  • Closures holding references — large arrays captured in callbacks
  • Global caches without eviction — use LRU cache with max size

Debug Unhandled Rejections

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  // In production, report to error tracking and exit
  process.exit(1);
});

Conditional Debugging

Use the debug module for toggleable logs:

const debug = require('debug');
const dbLog = debug('app:db');
const httpLog = debug('app:http');

dbLog('Query executed in %dms', duration);
httpLog('Request: %s %s', method, path);

Enable with: DEBUG=app:* node server.js

For production debugging, Bugsly captures unhandled exceptions and rejections with full context, eliminating the need to reproduce issues locally.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free