In this tutorial, you will learn the easiest and most efficient way to debug Node.js application code.
So let's get started.
Want to watch the video version of this tutorial? You can check out the video below:
How We Usually Debug Node.js Application
If we want to debug any Node.js application, usually we add a console.log
statement in the code that we want to debug to find out the value of any variable.
It works but you need to keep checking the console log to see the value that you're trying to print.
But If the data printed in the console contains nested objects or if it's a lot of data then using console.log
is not feasible.
So there is a better way.
Adding Debugger To Debug The Code
Instead, we can add a debugger;
statement in the code that we want to debug.
So let's say we have an Express.js API route for registering a user as shown in the code below:
// controllers/auth.js
const register = async (req, res) => {
try {
const { email, password } = req.body;
const existingUser = await User.findOne({
email,
});
if (existingUser) {
return res.status(400).send('User with the provided email already exist');
}
// some more code
return res.status(201).send();
} catch (error) {
console.log(error);
return res
.status(500)
.send('Error while registering a new user. Try again later.');
}
};
module.exports = { register };
// routes/auth.js
const { register } = require('../controllers/auth');
const Router = express.Router();
Router.post('/api/register', register);
And there is some issue while registering a user so we want to debug the register
function code.
In that case, you can just add a debugger;
statement inside the register
function code like this:
const register = async (req, res) => {
try {
const { email, password } = req.body;
debugger;
const existingUser = await User.findOne({
email,
});
if (existingUser) {
return res.status(400).send('User with the provided email already exist');
}
// some more code
return res.status(201).send();
} catch (error) {
console.log(error);
return res
.status(500)
.send('Error while registering a new user. Try again later.');
}
};
How To Run The Application For Debugging
Normally, we start our Node.js application by executing the following command:
node index.js
but instead, you can execute the following command:
node inspect index.js
Here, we just added an inspect
keyword in between.
If your main application file name is
server.js
you can executenode inspect server.js
command
Once you execute the above command, you will see the output displayed as shown below:
As you can see from the output, the debugger is attached, so now we can start debugging the code.
To do that, open the Chrome browser and enter chrome://inspect
in the browser URL.
You will see the output as shown below:
as we have executed node inspect index.js
command to start inspecting, you can see a new target entry displayed under the Remote Target
section.
Now, If you click on the displayed blue inspect
link, then you will see a new browser dev tool opened as shown below:
As you can see in the right panel in the above image, Debugger paused
message is displayed, and the debugging control is at the first line of code as you can see from the highlighted yellow line.
But we don't want to start debugging from the first line of code, instead, we want to just debug the registration code, so click on the blue triangle icon which is displayed just above the Debugger paused
message as shown below:
Now don't close this window, instead try registering a user from the application or by making an API call using Postman, so the /register
route handler code that we added previously will be executed.
As you can see above, when we click on create new account button, we're automatically redirected to the code where we added the debugger;
statement.
Now, we can debug the code line by line and see the values of each variable during debugging to find out and fix the issue.
Accessing Variables During Debugging
Sometimes when we mouse over any variable while debugging to see its actual value, the value might be too long because it might be an object with many properties, so we can't see it easily by doing mouseover.
In that case, while the debugger is still active, we can open the console tab and type the name of the variable whose value we want to see as you can see in the below Gif:
So that's how we can easily debug any of the Node.js application code.
Creating Script To Debug
If you don't want to manually type the node inspect index.js
command every time in the terminal, you can create a new debug
script inside the package.json
file like this:
"scripts": {
"start": "node index.js",
"debug": "node inspect index.js",
"dev": "nodemon index.js"
},
So now, you can execute npm run debug
command to start your application in debug mode.
Quick Recap
To debug a Node.js application, you need to follow the below steps:
Add a
debugger
statement inside the code that you want to debugRun
node inspect index.js
ornode inspect server.js
command to start the application in debug modeAccess the URL
chrome://inspect
in your Chrome browserClick on the
inspect
link under theRemote Target
sectionClick on the blue triangle icon to skip debugging, If you don't want to start debugging your application from the first line of
index.js
orserver.js
fileMake an API call or do something that will trigger the code, where you added the
debugger;
statementThis way you can debug the code line by line and find out the issue
Thanks for Reading
That's it for this tutorial. I hope you learned something new.
Want to watch the video version of this tutorial? You can check out this video.
If you want to master JavaScript, ES6+, React, and Node.js with easy-to-understand content, check out my YouTube channel. Don't forget to subscribe.
Want to stay up to date with regular content on JavaScript, React, and Node.js? Follow me on LinkedIn.
Top comments (0)