Debugging

Inspect running code with the built-in Node debugger.

Syntaxnode --inspect app.js

Beyond console.log, Node has a real debugger. Start your program with the --inspect flag and connect Chrome DevTools or your editor to set breakpoints and step through code.

Options

  • node --inspect app.js — attach a debugger.
  • node --inspect-brk app.js — pause on the first line.
  • The debugger; statement — a breakpoint in code.

Example

Example · javascript
function calculate(a, b) {
  const sum = a + b;
  debugger; // execution pauses here under --inspect
  return sum * 2;
}

console.log(calculate(3, 4)); // 14

When to use it

  • A developer uses `node --inspect` and Chrome DevTools to set breakpoints inside an Express middleware that processes malformed JSON payloads.
  • A CI pipeline runs tests with `--inspect-brk` so a developer can remotely attach a debugger the moment a flaky test begins.
  • An SRE uses `node --prof` to generate a CPU profile of a production-like workload, then `node --prof-process` to find the hot function causing high latency.

More examples

Start the Node.js inspector

Launches Node with the V8 inspector enabled -- open `chrome://inspect` to attach Chrome DevTools.

Example · bash
# Attach Chrome DevTools at chrome://inspect
node --inspect server.js

# Break on the first line (wait for debugger)
node --inspect-brk server.js

Debug with VS Code launch config

A VS Code `launch.json` configuration that starts the app with the debugger attached and loads env vars.

Example · json
{
  "version": "0.2.0",
  "configurations": [{
    "type":    "node",
    "request": "launch",
    "name":    "Debug API",
    "program": "${workspaceFolder}/src/index.js",
    "envFile": "${workspaceFolder}/.env"
  }]
}

Conditional debug logging

Uses the `debug` package to emit namespaced log lines that are silent by default and enabled via the `DEBUG` env var.

Example · js
const debug = require('debug')('app:auth');

function verifyToken(token) {
  debug('Verifying token: %s', token.slice(0, 8));
  // ...
}

// Enable in shell:
// DEBUG=app:auth node server.js

Discussion

  • Be the first to comment on this lesson.