Back to roadmaps nodejs Course

Debugging Node.js Applications

Relying solely on console.log for debugging is slow and inefficient for complex errors. Learning to use professional debugging tools allows you to inspect variable states, pause execution, and analyze call stacks interactively.


1. Node.js Inspector Option (--inspect)

Node.js has a built-in debugging inspector. To enable it, start your application with the --inspect flag:

# Start script with inspector enabled on default port 9229
node --inspect index.js

If you want to pause execution at the very first line of code (giving you time to set breakpoints before any code runs), use the --inspect-brk flag:

# Start and pause execution immediately
node --inspect-brk index.js

2. Debugging with Chrome DevTools

Once you launch Node.js with the inspector enabled:

  1. Open Google Chrome.
  2. Enter chrome://inspect in the address bar.
  3. You will see your Node.js application listed under Remote Target.
  4. Click inspect to open Chrome DevTools.
  5. In the Sources tab, you can add breakpoints, step over/into code blocks, and check active variables in the scope panels.

3. Configuring VS Code Debugger

VS Code has built-in debugging support for Node.js. Setting up a configuration file allows you to start debugging with a single click or keypress.

Create a file named .vscode/launch.json in your project root:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceFolder}/src/index.js",
      "env": {
        "NODE_ENV": "development"
      }
    }
  ]
}

Now, press F5 in VS Code to start debugging. You can set breakpoints directly inside the editor sidebar.


4. Debugging Uncaught Exceptions

To find out exactly where your application crashed without wrapping everything in try-catch blocks, configure VS Code to break on all uncaught exceptions in the bottom-left Breakpoints tab.

Alternatively, register event listeners inside your script to intercept and log these events before the process exits:

// Intercept all uncaught runtime promise rejections
process.on("unhandledRejection", (reason, promise) => {
  console.error("Unhandled Rejection detected at:", promise, "reason:", reason);
  // Perform cleanup tasks here
});

// Intercept all synchronous runtime errors
process.on("uncaughtException", (err) => {
  console.error("Uncaught Exception thrown:", err.message);
  process.exit(1); // Force exit program safely
});
Published on Last updated: