Skip to main content

Dev tools and workflow · Intermediate · 25 min

Debug a Node.js server with the inspector, breakpoints and VS Code

By Padding · Updated 18 Nov 2026
Node.js 26.13 LTS · node:26 image · TypeScript 7.0 · Chrome DevTools and VS Code, November 2026

You will find a real bug in a small Node.js 26 API by pausing it with the inspector, from Chrome DevTools, from the terminal and from VS Code, then read a TypeScript crash at the right line with source maps.

On this page

console.log gets you a long way, but on a server it has a cost: you edit, restart, send a request, read the output, and do it all again for the next variable. The inspector removes that loop. Start Node.js with one flag and a debugger can attach to the running process, stop it on any line while it serves a real request, and show you every variable in scope at that moment.

Debug JavaScript in Chrome DevTools covers code running in a web page. This tutorial is about the other side: a Node.js process with no page at all. You will build a small parcel-quote API with a real bug in it, then track the bug down three ways, from Chrome DevTools, from the node inspect debugger in the terminal and from VS Code. Last, you will read a crash in compiled TypeScript and make the stack trace point at your .ts file instead of the generated JavaScript.

Everything runs on your own machine with Node.js 26 and no npm packages, apart from TypeScript in the final step.

Step 1 · Build a small API with a bug in it

Create a demo folder and mark it as an ES module project:

Bash
mkdir -p ~/inspector-demo
cd ~/inspector-demo
cat > package.json <<'JSON'
{
  "name": "inspector-demo",
  "private": true,
  "type": "module"
}
JSON

The API quotes a delivery price for a list of parcels. Each parcel has a destination city and a weight, and the price per kilogram comes from a lookup that waits a little, standing in for a database query. Put the pricing logic in quote.js:

Bash
cat > quote.js <<'JS'
import { setTimeout as wait } from "node:timers/promises";

// Price per kilogram for each destination city, in US cents.
const RATES = new Map([
  ["lagos", 350],
  ["accra", 420],
  ["nairobi", 510],
]);

async function lookupRate(city) {
  await wait(20); // stands in for a database query
  return RATES.get(city);
}

export async function quoteTotal(parcels) {
  let total = 0;
  for (const { city, kg } of parcels) {
    const rate = await lookupRate(city);
    total += rate * kg;
  }
  return total;
}
JS

Line 19, total += rate * kg;, is the line you will stop on later. Now the HTTP server in server.js. It reads parcels from the query string in the form city:kg,city:kg and listens only on 127.0.0.1:

Bash
cat > server.js <<'JS'
import { createServer } from "node:http";
import { quoteTotal } from "./quote.js";

const port = Number(process.env.PORT ?? 3000);

function parseParcels(text) {
  return text.split(",").filter(Boolean).map((item) => {
    const [city, kg] = item.split(":");
    return { city, kg: Number(kg) };
  });
}

createServer(async (req, res) => {
  const url = new URL(req.url, "http://localhost");
  if (url.pathname !== "/quote") {
    res.writeHead(404).end();
    return;
  }
  try {
    const parcels = parseParcels(url.searchParams.get("parcels") ?? "");
    const totalCents = await quoteTotal(parcels);
    res.writeHead(200, { "content-type": "application/json" });
    res.end(JSON.stringify({ parcels: parcels.length, totalCents }) + "\n");
  } catch (err) {
    res.writeHead(400, { "content-type": "application/json" });
    res.end(JSON.stringify({ error: err.message }) + "\n");
  }
}).listen(port, "127.0.0.1", () => {
  console.log(`Quote API on http://127.0.0.1:${port}`);
});
JS

Start it in your second terminal, from the same folder:

Bash
cd ~/inspector-demo
node server.js

Back in the first terminal, ask for a quote for three parcels. Two kilograms to Lagos is 700 cents, one to Accra is 420 and three to Nairobi is 1,530, so the right answer is 2,650:

Bash
curl -s "http://127.0.0.1:3000/quote?parcels=lagos:2,Accra:1,nairobi:3"

Check it worked

The server terminal prints Quote API on http://127.0.0.1:3000, and the request returns {"parcels":3,"totalCents":null}. That null is the bug: JSON.stringify writes NaN as null, so somewhere a number became NaN. Stop the server with Ctrl+C before the next step. Each step uses its own port, so a server you forgot to stop cannot answer for the new one.

Step 2 · Start Node.js with the inspector

Run the same server with --inspect. With no value, the flag listens on 127.0.0.1:9229:

Bash
PORT=3001 node --inspect server.js

Before the Quote API line, Node prints Debugger listening on ws://127.0.0.1:9229/ followed by a random ID, and a link to the Node.js debugging guide. The ID is part of the address, so a client has to know it to connect. Debuggers find it through a small HTTP endpoint on the same port. Ask it yourself from the first terminal:

Bash
curl -s http://127.0.0.1:9229/json/list

The app still answers as before, because --inspect does not pause anything until a debugger asks it to:

Bash
curl -s "http://127.0.0.1:3001/quote?parcels=lagos:2"

Pause before the first line

--inspect lets the program run straight away, which suits a server you debug while it handles requests. When the bug is in start-up code, use --inspect-brk instead: Node waits on the first line of your script until a debugger attaches and tells it to go on. --inspect-wait also waits for a debugger, but does not stop on the first line once one attaches. Both take the same optional host:port, so you can give a second process its own port:

Bash
PORT=3009 node --inspect-brk=127.0.0.1:9230 server.js

With --inspect-brk, the /json/list endpoint answers on port 9230 but the API on port 3009 does not, because the code that starts listening has not run yet. Stop that process with Ctrl+C and keep the --inspect one on port 3001 running.

Never put the inspector on the network

Anyone who can connect to the inspector port can run any code they like inside your process, with its files, environment variables and database connections. There is no password. The Node.js documentation warns against binding it to a public address, and --inspect=0.0.0.0:9229 does exactly that. Keep the default 127.0.0.1 on servers. To debug a remote process, leave it on 127.0.0.1 there and forward the port over SSH from your laptop (replace you@your-server with your own login):

Bash
ssh -N -L 9229:127.0.0.1:9229 you@your-server

While that runs, 127.0.0.1:9229 on your laptop reaches the server's inspector through the encrypted SSH connection, and nothing new is open to the internet. Inside Docker, the process has to listen on 0.0.0.0 within the container, so publish the port to the host's loopback only, with -p 127.0.0.1:9229:9229, never -p 9229:9229. Do not leave --inspect in a production start command.

Check it worked

/json/list returns a JSON array with one entry, something like "type": "node", a "url" ending in server.js, and a "webSocketDebuggerUrl" starting with ws://127.0.0.1:9229/. The quote request returns {"parcels":1,"totalCents":700}.

Step 3 · Attach Chrome DevTools and stop on a line

Open a new Chrome tab and go to chrome://inspect (edge://inspect in Edge). Under Remote Target, your server is listed by its file path. If it is missing, click Configure and check that localhost:9229 is in the list. Click inspect under the target, or Open dedicated DevTools for Node, which reconnects by itself when you restart the process.

A DevTools window opens, attached to the server, not to a page. In the Sources panel, press Ctrl+P (Cmd+P on macOS), type quote.js and open it. Click the line number 19, next to total += rate * kg;. A blue marker shows the breakpoint.

Now send the failing request again from the first terminal. It hangs, because the server is paused:

Bash
curl -s "http://127.0.0.1:3001/quote?parcels=lagos:2,Accra:1,nairobi:3"

DevTools highlights line 19. The Scope pane on the right lists the local variables: city is "lagos", kg is 2 and rate is 350. Everything is fine for the first parcel. Press F8 (or click the resume button) to continue. The debugger stops on line 19 again for the second parcel, and this time city is "Accra" and rate is undefined. undefined * 1 is NaN, and NaN plus anything stays NaN. The rates are stored under lower-case names, and the request sent Accra with a capital letter.

Press F8 once more to let the third parcel through, and curl prints its answer.

Check it worked

You saw the debugger stop three times on line 19, and on the second stop the Scope pane showed rate: undefined next to city: "Accra". Leave DevTools attached for the next step.

Step 4 · Stop only when it matters, with conditions and logpoints

Stopping on every parcel is fine for three. For a request with 300 parcels you want the debugger to stop only on the bad one. Right-click the blue marker on line 19, choose Edit breakpoint, and pick Conditional breakpoint (on a line with no breakpoint, right-click the number and choose Add conditional breakpoint). Type the condition and press Enter:

JavaScript
rate === undefined

The marker turns orange. Send the same request again. DevTools stops once, on Accra, and lets Lagos and Nairobi through without pausing.

Sometimes you want to see values for every parcel without stopping at all. That is a logpoint: a breakpoint that writes to the console and carries on. Remove the conditional breakpoint by clicking its marker, then right-click line number 19 and choose Add logpoint. The text you type is the argument list of a console.log call:

JavaScript
"quote", city, kg, rate

The marker turns pink. Send the request once more and open the Console panel in DevTools. One line appears per parcel, and the process never pauses.

A logpoint beats a console.log you add to the file because nothing changes on disk, and you do not restart the server, so state built up in memory survives. Breakpoints and logpoints set this way disappear when the debugger disconnects.

Check it worked

With the conditional breakpoint, the request paused once, with city showing "Accra". With the logpoint, the Console shows three lines, quote lagos 2 350, quote Accra 1 undefined and quote nairobi 3 510, and curl answers at once. Close DevTools and stop the server with Ctrl+C.

Step 5 · Debug from the terminal with node inspect and step through async code

Node.js ships a small debugger of its own. It speaks the same protocol as DevTools, but runs in a terminal, so it works over a plain SSH session on a server with no desktop. On a slow or metered link, such as prepaid mobile data, that matters: it sends a few lines of text per command, where a remote desktop streams pixels.

A debugger; statement in your code is a breakpoint written in the source. It does nothing when no debugger is attached, and pauses the process when one is. Rewrite quote.js with one just before the rate lookup, on line 18:

Bash
cd ~/inspector-demo
cat > quote.js <<'JS'
import { setTimeout as wait } from "node:timers/promises";

// Price per kilogram for each destination city, in US cents.
const RATES = new Map([
  ["lagos", 350],
  ["accra", 420],
  ["nairobi", 510],
]);

async function lookupRate(city) {
  await wait(20); // stands in for a database query
  return RATES.get(city);
}

export async function quoteTotal(parcels) {
  let total = 0;
  for (const { city, kg } of parcels) {
    debugger;
    const rate = await lookupRate(city);
    total += rate * kg;
  }
  return total;
}
JS

Start the server under node inspect in your second terminal. By default it stops on the first line of server.js. NODE_INSPECT_RESUME_ON_START=1 tells it to run until the first breakpoint instead:

Bash
NODE_INSPECT_RESUME_ON_START=1 PORT=3002 node inspect server.js

You get a debug> prompt and the Quote API on http://127.0.0.1:3002 line. From the first terminal, ask for one parcel to Accra:

Bash
curl -s "http://127.0.0.1:3002/quote?parcels=Accra:1"

The debugger stops on the debugger; line. Type the commands after each debug> prompt. n (next) steps to the next line, and exec evaluates an expression where the code is paused:

Text
break in file:///home/you/inspector-demo/quote.js:18
 16   let total = 0;
 17   for (const { city, kg } of parcels) {
>18     debugger;
 19     const rate = await lookupRate(city);
 20     total += rate * kg;
debug> n
break in file:///home/you/inspector-demo/quote.js:19
debug> n
break in file:///home/you/inspector-demo/quote.js:20
debug> exec city
'Accra'
debug> exec rate
undefined
debug> c

The second n is the interesting one. Line 19 contains an await, so the function hands control back to the event loop while the 20 millisecond lookup runs. Stepping over it does not drop you into Node's timer internals: the debugger waits for the promise to settle and stops on the next line of the same function. While it waits, other requests can run, so with real traffic you can see other code between two steps of yours.

The other movement commands are s (step into the function called on this line, such as lookupRate), o (step out to the caller) and c (continue to the next breakpoint). bt prints the call stack, and sb('quote.js', 20, 'rate === undefined') sets a conditional breakpoint without editing the file. In DevTools and VS Code the same moves are F10 (step over), F11 (step into), Shift+F11 (step out) and F8 or F5 (continue).

Check it worked

After the second n, the debugger reports line 20 of quote.js, exec city prints 'Accra' and exec rate prints undefined. After c, the curl in the first terminal prints {"parcels":1,"totalCents":null}. Type .exit to leave the debugger, which also stops the server.

Step 6 · Fix the bug and confirm it

You now know the cause: city names arrive in whatever case the caller typed, and the lookup expects lower case. Normalise the name, and fail loudly for a city with no rate, so the next bad input gives a clear error instead of null. Rewrite quote.js, which also removes the debugger; statement. Never ship one: it does nothing without a debugger, but it will stop the process the day someone attaches one in production.

Bash
cd ~/inspector-demo
cat > quote.js <<'JS'
import { setTimeout as wait } from "node:timers/promises";

// Price per kilogram for each destination city, in US cents.
const RATES = new Map([
  ["lagos", 350],
  ["accra", 420],
  ["nairobi", 510],
]);

async function lookupRate(city) {
  await wait(20); // stands in for a database query
  const rate = RATES.get(city.trim().toLowerCase());
  if (rate === undefined) {
    throw new Error(`No rate for ${city}`);
  }
  return rate;
}

export async function quoteTotal(parcels) {
  let total = 0;
  for (const { city, kg } of parcels) {
    const rate = await lookupRate(city);
    total += rate * kg;
  }
  return total;
}
JS

toLowerCase is fine for these names. If your data has accented or non-Latin city names, normalise them the same way when you store and when you look up, for example with toLocaleLowerCase and normalize("NFC"), so two spellings of the same name cannot drift apart. Start the server in the second terminal:

Bash
PORT=3003 node server.js

Then send the original request and one with a city that has no rate:

Bash
curl -s "http://127.0.0.1:3003/quote?parcels=lagos:2,Accra:1,nairobi:3"
curl -s "http://127.0.0.1:3003/quote?parcels=Kumasi:1"

Check it worked

The first request returns {"parcels":3,"totalCents":2650}, the total you worked out by hand. The second returns {"error":"No rate for Kumasi"} with status 400. Stop the server with Ctrl+C.

Step 7 · Launch and attach from VS Code

VS Code's built-in JavaScript debugger uses the same inspector. A .vscode/launch.json file stores named ways to start debugging, so nobody on the team retypes flags. Create one with three configurations, a launch, an attach and one for the TypeScript build in the next step:

Bash
cd ~/inspector-demo
mkdir -p .vscode
cat > .vscode/launch.json <<'JSON'
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch quote API",
      "program": "${workspaceFolder}/server.js",
      "env": { "PORT": "3004" },
      "skipFiles": ["<node_internals>/**"]
    },
    {
      "type": "node",
      "request": "attach",
      "name": "Attach to inspector on 9229",
      "address": "127.0.0.1",
      "port": 9229,
      "skipFiles": ["<node_internals>/**"]
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Launch label script (TypeScript)",
      "program": "${workspaceFolder}/label/dist/label.js",
      "outFiles": ["${workspaceFolder}/label/dist/**/*.js"],
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}
JSON
node -p 'JSON.parse(require("node:fs").readFileSync(".vscode/launch.json", "utf8")).configurations.map((c) => c.request + ": " + c.name).join("\n")'

What the settings do:

  • request: "launch" makes VS Code start Node.js with the inspector itself and attach at once. program is the entry file and env sets environment variables for it.
  • request: "attach" connects to a process you started yourself with node --inspect, on the address and port given. Use it for a process started by another tool, or through the SSH tunnel from earlier.
  • skipFiles with <node_internals>/** keeps step into from wandering through Node's own code.
  • outFiles tells VS Code where the compiled JavaScript lives, so it can read the source maps next to it and put your breakpoints in the .ts files.

Open the ~/inspector-demo folder in VS Code, open the Run and Debug view, pick Launch quote API and press F5. Click in the gutter left of a line number to set a breakpoint. Right-click the gutter for Add Conditional Breakpoint and Add Logpoint. VS Code's logpoint message is plain text with expressions in braces, such as quote {city} {kg}kg rate {rate}, and it appears in the Debug Console.

Check it worked

The node -p command prints the three configurations, launch: Launch quote API, attach: Attach to inspector on 9229 and launch: Launch label script (TypeScript), which proves the file is valid JSON. In VS Code, F5 on the first one starts the server, the status bar changes colour, and a request to http://127.0.0.1:3004/quote?parcels=lagos:1 stops on any breakpoint you set in quote.js. Stop debugging with Shift+F5.

Step 8 · Read a TypeScript crash at the right line with source maps

When you run compiled TypeScript, Node.js runs the generated JavaScript, so stack traces point at lines in dist/, which you never edit. Source maps link each generated position back to the .ts file, and --enable-source-maps makes Node use them in stack traces. Set up a small TypeScript 7 project in a subfolder. Set up a TypeScript 7 project explains each setting:

Bash
mkdir -p ~/inspector-demo/label/src
cd ~/inspector-demo/label
cat > package.json <<'JSON'
{
  "name": "label-demo",
  "private": true,
  "type": "module"
}
JSON
npm install --save-dev typescript@7.0.2 @types/node@26
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "es2023",
    "module": "nodenext",
    "rootDir": "src",
    "outDir": "dist",
    "strict": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "types": ["node"]
  },
  "include": ["src"]
}
JSON

"sourceMap": true is the setting that matters here: next to each dist/*.js file, the compiler writes a .js.map file. Now a script that prints shipping labels, and throws on the second parcel, which has no weight. The throw is on line 8 of the TypeScript file:

Bash
cat > src/label.ts <<'TS'
interface Parcel {
  city: string;
  kg: number;
}

export function labelFor(parcel: Parcel): string {
  if (parcel.kg <= 0) {
    throw new RangeError(`Parcel to ${parcel.city} has no weight`);
  }
  return `${parcel.city.toUpperCase()} | ${parcel.kg} kg`;
}

console.log(labelFor({ city: "Accra", kg: 1.5 }));
console.log(labelFor({ city: "Lagos", kg: 0 }));
TS
npx tsc
ls dist

Run the build without source maps, then with them. The script crashes on purpose, so each command reports its exit code:

Bash
node dist/label.js || echo "exit code: $?"
node --enable-source-maps dist/label.js || echo "exit code: $?"

Both runs print ACCRA | 1.5 kg, then RangeError: Parcel to Lagos has no weight. In the first run the trace points at a line in dist/label.js, a lower number than 8 because the compiler removed the interface. In the second, the top frame reads something like at labelFor (file:///home/you/inspector-demo/label/src/label.ts:8:11), the line you would open and fix.

To get the same in production logs, start the compiled app with node --enable-source-maps dist/server.js, or set NODE_OPTIONS=--enable-source-maps where it runs. Ship the .js.map files with the build. The Node.js documentation notes that the option can slow down code that reads error.stack very often, so measure if your app creates errors in a hot path.

In VS Code, the Launch label script (TypeScript) configuration from the previous step runs dist/label.js, and, thanks to outFiles and the maps, a breakpoint set on line 8 of src/label.ts stops there. Run npx tsc again after each change, because the debugger runs the compiled output.

Check it worked

ls dist lists label.js and label.js.map. The first run's trace names dist/label.js, the second names src/label.ts:8, and both end with exit code: 1.

Step 9 · Clean up

Stop any server still running in the second terminal with Ctrl+C, and close any DevTools window attached to it. Then remove the demo folder, which also removes the TypeScript packages installed inside it. Node.js stays installed:

Bash
cd ~
rm -rf ~/inspector-demo

Check it worked

ls ~/inspector-demo reports that there is no such file or directory, and curl -s http://127.0.0.1:9229/json/list gets no answer, so no inspector is left listening.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.