Debugging Express Applications

1. Using Debug Module

Example: DEBUG env

DEBUG=express:* node app.js
DEBUG=express:router,express:application node app.js
DEBUG=app:* node app.js

2. Enabling Express Debug Output

NamespaceWhat it logs
express:applicationApp init / settings
express:routerRoute matching
express:router:layerMiddleware execution
express:viewView rendering

3. Using Node.js Debugger

Example: --inspect

node --inspect app.js
node --inspect-brk app.js   # break on first line
node --inspect=0.0.0.0:9229 app.js  # remote

4. Setting Breakpoints

Example: debugger statement

app.get("/users/:id", (req, res) => {
  debugger;  // pauses when devtools attached
  res.json(getUser(req.params.id));
});

5. Using console.log() Statements

Example: Tagged logs

console.log("[users]", { id: req.params.id, query: req.query });
console.error("[users] failed", err);
Warning: Remove or downgrade console.log in production — use logger.debug() with a level switch instead.

6. Installing morgan for Logging

Example: morgan dev

app.use(morgan("dev"));  // GET /users 200 4.231 ms - 432

7. Using VS Code Debugger

Example: launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Express",
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceFolder}/src/server.js",
      "envFile": "${workspaceFolder}/.env"
    }
  ]
}

8. Inspecting Request/Response Objects

Example: console.dir

console.dir(req, { depth: 1, colors: true });
console.dir({ headers: req.headers, body: req.body }, { depth: null });

9. Using Chrome DevTools

Example: chrome://inspect

# 1. node --inspect app.js
# 2. open chrome://inspect
# 3. click "inspect" under Remote Target

10. Analyzing Stack Traces

Example: source-map-support

// node 20+ has built-in source maps with --enable-source-maps
// node --enable-source-maps dist/server.js
FlagEffect
--enable-source-mapsMap stack traces back to TS/source
--stack-trace-limit=50Show more frames
Error.captureStackTraceSkip wrapper frames in custom errors

11. Using nodemon for Auto-Restart

Example: node native watch

# Node 20+ — no nodemon needed:
node --watch --env-file=.env src/server.js

# Or nodemon:
npx nodemon src/server.js