Sub topic 11
Debugging in DevTools and the Node.js Inspector
This chapter assumes you can load a script in a web page, run a file with node, and write ES modules with import and export. You should also be comfortable with promises and async/await. Both runtimes share one debugging model, and the same Chrome DevTools interface works with each. Once you learn it in one place, you can use it in the other.
The Working Model: Pause, Inspect, Step
A debugger pauses the engine at a chosen point. While the engine is paused, you can read every variable in scope, walk the call stack, and run expressions against the live program state. Then you resume the program or advance it one step at a time.
The browser builds the debugger into DevTools. Node.js exposes the same capability through the inspector, a server inside the Node process that speaks the Chrome DevTools Protocol (CDP). CDP is a JSON message format sent over a WebSocket. Chrome DevTools, VS Code, and Node's own command-line debugger are all CDP clients. That shared protocol is why the interface looks the same in both environments.
A Bug to Debug
The examples below use one small module with a deliberate off-by-one error. It runs unchanged in both environments.
// cart.mjs
export function total(items) {
let sum = 0;
for (let i = 0; i <= items.length; i++) {
sum += items[i].price * items[i].qty;
}
return sum;
}// main.mjs
import { total } from './cart.mjs';
const items = [
{ name: 'pen', price: 2, qty: 3 },
{ name: 'book', price: 12, qty: 1 },
];
console.log('total:', total(items));Running node main.mjs prints TypeError: Cannot read properties of undefined (reading 'price'). The stack trace tells you where the error happened. A debugger tells you why: on the last pass through the loop, i equals items.length, so items[i] is undefined.
To run the same code in a browser, load it with <script type="module" src="main.mjs"></script> from a page served over HTTP. Most browsers block module scripts loaded from file:// URLs. Any static server works, for example npx serve ..
Debugging in Browser DevTools
Open DevTools with F12, or with Cmd+Option+I on macOS. The Sources panel is the debugger. The other panels support it: Console for expressions and logs, and Network for requests.
Breakpoints
Click a line number in Sources to set a line breakpoint. Right-click a line number to reach the other kinds.
| Breakpoint type | Where to set it | Pauses when |
|---|---|---|
| Line | Click a line number | Execution reaches that line |
| Conditional | Right-click line, "Add conditional breakpoint" | The line runs and the expression is truthy |
| Logpoint | Right-click line, "Add logpoint" | Never pauses; logs the expression to the Console |
| `debugger;` statement | In your source code | DevTools is open and the statement runs |
| Pause on exceptions | Sources panel toolbar | Any exception is thrown (or only uncaught ones) |
| DOM change | Elements panel, right-click a node, "Break on" | A subtree, attribute, or the node itself changes |
| Event listener | Sources, "Event Listener Breakpoints" | A listener for a chosen event (such as `click`) runs |
| Fetch/XHR | Sources, "XHR/fetch Breakpoints" | A request URL contains the given string |
For the cart bug, a conditional breakpoint on the sum += line with the condition i === items.length pauses only on the bad pass through the loop. Without the condition, you would have to resume once for every item. A logpoint with the expression 'i', i, items[i] shows every pass in the Console without pausing.
While Paused
The right-hand sidebar shows the program state at the pause:
- Scope lists local, closure, module, and global variables. You can edit a value by double-clicking it.
- Call Stack lists the active frames. Click a frame to inspect its variables.
- Watch re-evaluates expressions you add, such as
items[i], at every pause. - The Console evaluates code in the selected frame, so typing
items.lengthreturns the live value.
The stepping controls are Resume (F8), Step over (F10), Step into (F11), and Step out (Shift+F11). Step over runs the current line, including any functions it calls, and stops at the next line. Step into enters the function being called.
Async Stack Traces
When you pause inside a .then callback or after an await, the real call stack holds only the event loop's microtask runner. DevTools stitches in async frames to show which code scheduled the callback. They appear in the Call Stack under labels such as "await" or "setTimeout". Node.js does something similar in error.stack: when an error passes through async functions, the trace includes at async functionName lines.
Source Maps
If you ship minified or bundled code, DevTools shows unreadable source unless a source map is available. A source map is a .map file that links each position in the generated code to its position in the original source. Bundlers produce source maps when configured to do so. The generated file points to its map with a trailing //# sourceMappingURL=app.js.map comment, and DevTools then lets you set breakpoints in the original files. Node.js also reads source maps when you pass --enable-source-maps, which rewrites stack traces to point at the original lines.
Debugging in Node.js
Starting the Inspector
| Flag | Behavior |
|---|---|
| `--inspect` | Starts the inspector and runs the script immediately |
| `--inspect-brk` | Starts the inspector and pauses before the first line of user code |
| `--inspect-wait` | Waits for a debugger to attach, then runs without pausing (Node.js 22 and later) |
| `--inspect=9230` | Uses another port (the default is 9229) |
Use --inspect-brk for short scripts:
node --inspect-brk main.mjsNode prints a line like Debugger listening on ws://127.0.0.1:9229/3f1c.... Open chrome://inspect in Chrome, find your script under "Remote Target", and click inspect. A DevTools window opens, paused at the first line. Set a breakpoint in cart.mjs, press F8, and debug the program exactly as in the browser.
For a long-running server, --inspect is enough because the process stays alive until you attach. You can also turn on the inspector from inside a running program:
// late-inspect.mjs
import inspector from 'node:inspector';
inspector.open(9229, '127.0.0.1');
console.log('inspector at', inspector.url());
setInterval(() => {}, 1000); // keep the process aliveThe Built-in Terminal Debugger
When you have no browser available, such as over SSH, node inspect gives you a command-line CDP client:
node inspect main.mjsThe prompt is debug>. The most useful commands are listed below.
| Command | Action |
|---|---|
| `c` (or `cont`) | Continue to the next breakpoint |
| `n` (or `next`) | Step over |
| `s` (or `step`) | Step into |
| `o` (or `out`) | Step out |
| `sb('cart.mjs', 4)` | Set a breakpoint at line 4 of `cart.mjs` |
| `watch('i')` | Show `i` at every pause |
| `bt` | Print the backtrace |
| `repl` | Evaluate expressions in the current frame; Ctrl+C exits |
The debugger; statement works here too. Put one inside the loop, type c, and the debugger stops there.
Editors
VS Code has a built-in CDP client. Its "JavaScript Debug Terminal" attaches automatically to every node process you start from that terminal, so you don't need any flags.
Console Methods Worth Knowing
Logging still helps, especially for timing problems that pausing would disturb. Both runtimes implement these console methods:
const rows = [{ id: 1, ok: true }, { id: 2, ok: false }];
console.table(rows); // tabular view of an array of objects
console.dir({ a: { b: { c: { d: 1 } } } }, { depth: null }); // full nesting in Node.js
console.trace('how did we get here?'); // prints the current stack
console.time('work');
for (let i = 0; i < 1e6; i++);
console.timeEnd('work'); // e.g. "work: 1.8ms"
console.assert(rows.length === 3, 'expected 3 rows'); // logs only when falseNode prints nested objects only to a depth of 2 by default, and anything deeper appears as [Object]. The { depth: null } option prints the whole object. The browser Console shows live, expandable objects instead. Those objects are evaluated when you expand them, not when they were logged, so a later mutation can show up in an earlier log entry. To capture a snapshot, log structuredClone(obj) or JSON.stringify(obj).
Common Errors and Fixes
- The breakpoint is never hit in Node.js. The script finished before the debugger attached. Use
--inspect-brkor--inspect-wait. debugger;does nothing. The statement only pauses when a debugger is attached. In the browser, DevTools must be open. In Node.js, the process must have been started with an inspector flag.- "Address already in use" on port 9229. Another Node process holds the port. Stop that process or pass
--inspect=0to get a random free port. - Breakpoints land on the wrong lines. The source map is missing or stale. Rebuild the bundle and check the
sourceMappingURLcomment. - An old object value appears in the Console. The Console shows live objects. Log a copy instead.
Exercises
Exercise
You run node --inspect main.mjs, open chrome://inspect, and the target disappears before you can click it. What happened, and which flag fixes it?
Show answer
The short script ran to completion and exited before DevTools attached. Use --inspect-brk, which pauses before the first line of user code, or --inspect-wait, which waits for a client to attach before running.
Exercise
Write a conditional breakpoint condition for the sum += line in cart.mjs that pauses only on the loop pass that causes the TypeError, and state the fix to the code.
Show answer
Use the condition i === items.length (or items[i] === undefined). The fix is to change the loop test from i <= items.length to i < items.length.
Exercise
Why does the browser Console sometimes show a value that an object did not have when console.log ran, and how do you log the value it had at that moment?
Show answer
The Console keeps a live reference to the object and reads its properties when you expand it, so later changes show up. Log a snapshot with console.log(structuredClone(obj)) or console.log(JSON.stringify(obj)).
Exercise
A colleague wants to debug a Node.js server on a cloud VM from their laptop and suggests starting it with --inspect=0.0.0.0:9229. What is the risk, and what is the safer alternative?
Show answer
Anyone who can reach port 9229 can connect over CDP and run arbitrary code with the server's privileges. Keep the default 127.0.0.1 binding and forward the port through SSH with ssh -L 9229:127.0.0.1:9229 user@vm, then attach locally through chrome://inspect.