How to Debug Node.js in VS Code and Chrome
This article provides a straightforward guide on how to debug a Node.js application using two of the most popular development tools: Visual Studio Code and Google Chrome DevTools. You will learn how to launch your application in debug mode, set breakpoints, inspect variables, and step through your code in both environments to diagnose and resolve bugs quickly.
Debugging Node.js with VS Code
Visual Studio Code has built-in debugging support for the Node.js runtime, making it one of the easiest tools to use.
Method 1: Auto Attach (Fastest)
Open your project in VS Code.
Open the command palette (
Ctrl+Shift+Pon Windows/Linux orCmd+Shift+Pon macOS).Type and select Debug: Toggle Auto Attach.
Choose Only With Flag or Always.
Open the integrated terminal in VS Code and run your app using:
node --inspect index.jsVS Code will automatically attach its debugger to the process.
Method 2: Launch Configuration (Recommended for Projects)
Click on the Run and Debug icon on the Side Bar (or press
Ctrl+Shift+D/Cmd+Shift+D).Click on create a launch.json file and select Node.js.
VS Code will create a
.vscode/launch.jsonfile. Configure it as follows:{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": ["<node_internals>/**"], "program": "${workspaceFolder}/index.js" } ] }Set a breakpoint by clicking to the left of the line numbers in your JavaScript file.
Press F5 to start debugging. The execution will pause at your breakpoint, allowing you to inspect variables in the left sidebar.
Debugging Node.js with Chrome DevTools
If you prefer using browser-based tools, Google Chrome provides a dedicated interface to debug Node.js applications.
Step 1: Start Node.js with the Inspect Flag
Run your Node.js application from your terminal with the
--inspect flag:
node --inspect index.jsIf you want the application to pause on the very first line of code
before executing, use the --inspect-brk flag instead:
node --inspect-brk index.jsThe terminal will output a message indicating that the debugger is
listening on a specific WebSocket port (usually
ws://127.0.0.1:9229).
Step 2: Open Chrome DevTools
- Open Google Chrome.
- Type
chrome://inspectinto the address bar and press Enter. - Under the Devices section, you should see your Node.js process listed under “Remote Target”.
- Click the inspect link next to your target application. Alternatively, you can click the green Node icon in the top-left corner of any open Chrome DevTools window.
Step 3: Debug Your Code
- A dedicated DevTools window will open.
- Go to the Sources tab.
- Open your project files in the left pane.
- Click on a line number to set a breakpoint.
- Trigger the code execution (e.g., make an HTTP request to your local server).
- The debugger will pause at your breakpoint, allowing you to use the Scope, Call Stack, and Watch panels to analyze your application’s state.