Skip to main content
TutorialsTools & Productivity

Debugging Node.js Applications Like a Pro

Go beyond console.log. Master the Node.js debugger, memory profiling, async stack traces, and production debugging techniques.

Mbeah Essilfie

Mbeah Essilfie

April 30, 2026 at 06:04 AM

9 min read 1035 views
Debugging Node.js Applications Like a Pro

Beyond console.log

Console.log debugging works, but it's slow and messy. Professional debugging tools save hours.

The Built-In Debugger

# Start with debugger attached
node --inspect server.js

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

Then open chrome://inspect in Chrome, or use VS Code's debugger.

VS Code Launch Config

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Nuxt",
      "type": "node",
      "request": "launch",
      "command": "pnpm dev",
      "cwd": "${workspaceFolder}",
      "console": "integratedTerminal",
      "serverReadyAction": {
        "pattern": "Local:.*?(https?://\\S+)",
        "uriFormat": "%s",
        "action": "debugWithChrome"
      }
    }
  ]
}

Conditional Breakpoints

In VS Code, right-click the gutter → "Conditional Breakpoint":

// Only break when userId matches
userId === "abc-123"

// Only break on the 50th iteration
i === 49

// Only break when error occurs
error !== null

Async Stack Traces

# Enable long async stack traces
node --async-stack-traces server.js
// Or in code
Error.stackTraceLimit = 50 // Default is 10
Without async stack traces, errors in promises just show the immediate location. Enable them to see the full chain of async calls that led to the error.

Memory Leak Detection

# Generate a heap snapshot
node --inspect server.js
# Then in Chrome DevTools: Memory tab → Take Heap Snapshot

Common leak sources:

  • Event listeners never removed
  • Growing Maps/Sets without cleanup
  • Closures capturing large objects
  • Timers/intervals not cleared
// Quick leak detector
function trackMemory(label: string) {
  const usage = process.memoryUsage()
  console.log(`[${label}] Heap: ${Math.round(usage.heapUsed / 1024 / 1024)}MB`)
}

setInterval(() => trackMemory('periodic'), 10000)

Performance Profiling

# CPU profile for 5 seconds
node --prof server.js
# Process the output
node --prof-process isolate-*.log > profile.txt

Or use the built-in profiler:

import { performance, PerformanceObserver } from 'node:perf_hooks'

performance.mark('start-db')
const users = await db.user.findMany()
performance.mark('end-db')
performance.measure('db-query', 'start-db', 'end-db')

const obs = new PerformanceObserver((items) => {
  items.getEntries().forEach((entry) => {
    console.log(`${entry.name}: ${entry.duration.toFixed(2)}ms`)
  })
})
obs.observe({ entryTypes: ['measure'] })

Production Debugging

When you can't attach a debugger:

// 1. Structured logging with request IDs
function createRequestLogger(requestId: string) {
  return {
    info: (msg: string, data?: unknown) =>
      console.log(JSON.stringify({ requestId, level: 'info', msg, data })),
    error: (msg: string, error?: Error) =>
      console.error(JSON.stringify({ requestId, level: 'error', msg, stack: error?.stack })),
  }
}

// 2. Debug endpoint (protected!)
app.get('/debug/health', requireAdmin, (req, res) => {
  res.json({
    uptime: process.uptime(),
    memory: process.memoryUsage(),
    cpu: process.cpuUsage(),
    connections: server.connections,
  })
})

Tips

  • Use debugger statement for quick breakpoints
  • console.table() for arrays of objects
  • console.trace() for quick stack traces
  • console.time() / console.timeEnd() for timing
  • util.inspect(obj, { depth: null }) for deep objects

The fastest path to fixing a bug is understanding how to reproduce it and inspect the state at the right moment.

JavaScriptNode.jsPerformance
Mbeah Essilfie

Written by Mbeah Essilfie

Fullstack Software Developer

Read next

The Complete Guide to Vue 3 Composables
12 min read

The Complete Guide to Vue 3 Composables

Understand the power of Vue 3's Composition API through practical, real-world composable patterns that you can use today.

Mbeah EssilfieMbeah Essilfie
987