Inspector protocol

The Inspector Protocol (specifically the Chrome DevTools Protocol or CDP) is the bridge that allows external tools—like Chrome DevTools, VS Code, or automated scripts—to "look inside" a running Node.js process. It operates over a WebSocket connection using JSON-RPC.

1. How it Works


When you start Node.js with the --inspect flag, it opens a WebSocket server (usually on port 9229). The Inspector Protocol then allows a "Client" (the DevTools UI) to communicate with a "Backend" (the Node.js process).

  1. Commands: The client sends a JSON request (e.g., "Pause execution").

  2. Events: The backend sends a JSON notification (e.g., "Execution paused at line 42").


2. The node:inspector Module


While the --inspect flag is for external tools, Node.js provides a built-in inspector module that allows you to trigger these debugging features programmatically from within your own code.

Example: Taking a Heap Snapshot

You can use the protocol to programmatically capture memory data if you suspect a leak.


const inspector = require('node:inspector');
const fs = require('fs');

const session = new inspector.Session();
session.connect();

// Use the 'HeapProfiler' domain of the protocol
session.post('HeapProfiler.takeHeapSnapshot', (err, res) => {
  console.log('Snapshot taken!');
  session.disconnect();
});



DomainPurpose
DebuggerBreakpoints, stepping through code, and call stacks.
ProfilerCPU profiling to find slow functions.
HeapProfilerMemory snapshots and tracking allocations.
RuntimeEvaluating JavaScript expressions and inspecting objects.
ConsoleCapturing console.log messages sent by the app



3. Protocol Domains

The protocol is organized into Domains, each handling a specific part of the engine:


4. Common Flags


  • node --inspect: Starts the inspector. The app starts running immediately.

  • node --inspect-brk: Starts the inspector and breaks on the first line. This is essential for debugging startup logic.

  • node --inspect=0.0.0.0:9229: Allows remote connections (be careful: this is a security risk if exposed to the public internet).


5. Security Warning


The Inspector Protocol is extremely powerful—it can execute arbitrary code in your process.

  • Never leave the inspector open in a production environment.

  • Never bind the inspector to 0.0.0.0 on a public server; it should only be accessible via 127.0.0.1 (localhost) or through a secure SSH tunnel.


6. Beyond Debugging: Automation


Because the protocol is just JSON over WebSockets, you can write scripts to automate performance checks. Tools like Puppeteer use this exact protocol to control Chrome, and you can write similar logic to "crawl" your own Node.js backends for memory leaks or slow event loop cycles.

Getting Started with Node.js Debugging

This video provides a quick visual walkthrough of how to enable the inspector and connect it to Chrome DevTools for real-time debugging.