How to Debug Node.js Applications Using the debugger; Statement - Easiest Way
Tags: react, node, javascript
Published: 2024-04-30 06:57:39

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:

{% embed https://www.youtube.com/watch?v=B_oPWQ9Wyew %}

## 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:

```javascript
// 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:

```javascript
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:

```javascript
node index.js
```

but instead, you can execute the following command:

```javascript
node inspect index.js
```

Here, we just added an `inspect` keyword in between.

> If your main application file name is `server.js` you can execute `node inspect server.js` command

Once you execute the above command, you will see the output displayed as shown below:

![Starting Node.js Debugger Using Inspect](https://cdn.hashnode.com/res/hashnode/image/upload/v1713609952734/f916f875-33e1-4d54-b92d-24cfa017c0e8.png)

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:

![Chrome Inspect Result](https://cdn.hashnode.com/res/hashnode/image/upload/v1713610163221/5bf95ac7-f360-4c0d-9ef4-3667762c4d34.png)

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:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1713610476678/785acdbf-7a05-4fea-b0d6-b876df9325f4.png)

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:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1713610809816/63f5e9de-bb68-4997-81e7-4512d65ae870.gif)

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.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1713611715327/e82bfcb6-61aa-4737-b525-9bc9333c5dfc.gif)

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:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1713612358773/144e3ea6-bbb2-45d1-948f-5405ceb22e60.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:

```javascript
"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 debug
    
* Run `node inspect index.js` or `node inspect server.js` command to start the application in debug mode
    
* Access the URL `chrome://inspect` in your Chrome browser
    
* Click on the `inspect` link under the `Remote Target` section
    
* Click 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` or `server.js` file
    
* Make an API call or do something that will trigger the code, where you added the `debugger;` statement
    
* This 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.](https://www.youtube.com/watch?v=B_oPWQ9Wyew)

If you want to master JavaScript, ES6+, React, and Node.js with easy-to-understand content, check out my [YouTube channel](https://www.youtube.com/@codingmastery_dev/). Don't forget to subscribe.

Want to stay up to date with regular content on JavaScript, React, and Node.js? [Follow me on LinkedIn](https://www.linkedin.com/in/yogesh-chavan97/).

[![Build Full Stack Link Sharing App Using MERN Stack](https://cdn.hashnode.com/res/hashnode/image/upload/v1713614300163/0c5bd4bd-7de3-4358-80df-0322c5945b55.png)](https://www.youtube.com/watch?v=wcjCsMRZKxs)