5 Steps to debugging Next.js/Node.js from VSCode or Chrome DevTools
Tags: nextjs, debugging, vscode, devtools
Published: 2020-03-04 10:04:41

---
title: 5 Steps to debugging Next.js/Node.js from VSCode or Chrome DevTools
published: true
description: This article explains how to setup your developer environment so you can debug your Next.js application using Visual Studio Code or Chrome DevTools
tags: nextjs,debugging,vscode,devtools
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/i7bvaknfwihb0m3usqoj.jpg
---

**April 5, 2020 update**: This article is now part of the Next.js documentation: https://nextjs.org/docs/advanced-features/debugging

---

👋 Hi there, this article explains how to setup your developer environment so you can debug your Next.js application using [Visual Studio Code debugger](https://code.visualstudio.com/docs/editor/debugging) or [Chrome DevTools](https://developers.google.com/web/tools/chrome-devtools).

Since Next.js is a Node.js application, what's provided here as guidance will also work for any Node.js program.

When fully setup, you'll be able to put [breakpoints](https://en.wikipedia.org/wiki/Breakpoint) in both frontend (React) and backend code (Node.js, API routes). Then your favorite debugger will pop out whenever your code encounters your breakpoints.

**The whole tutorial takes 5 min**. When you'll be finished, you'll get this experience (VS Code, React):

![Demo of a Visual Studio Code debugging session in Next.js frontend code](https://dev-to-uploads.s3.amazonaws.com/i/nz0mlhsq726fz0txdzpj.gif)

_Table of contents:_
- [Mandatory introduction: why even bother?](#mandatory-introduction-why-even-bother)
- [Step one: create your Next.js debugging demo application](#step-one-create-your-nextjs-debugging-demo-application)
- [Step two: configure Next.js to start in debug mode](#step-two-configure-nextjs-to-start-in-debug-mode)
- [Step three: launch your application](#step-three-launch-your-application)
- [Step four: connect your debugging inspector](#step-four-connect-your-debugging-inspector)
  * [VS Code](#vs-code)
  * [Chrome DevTools](#chrome-devtools)
- [Step five: actually debug your application](#step-five-actually-debug-your-application)

# Mandatory introduction: why even bother?

I always thought that I don't need a debugger in JavaScript: I can just `console.log` my way out most of the time. The reason for this habit I believe is that JavaScript debugging tools were always kind of working but not really. In the browser at least it was working but then Node.js came and it was again very hard to debug it nicely. The whole debugging experience was painful and you spent more time switching windows than anything else.

Now after using VS Code to debug both my React and Node.js code I really think _it's way more powerful_ than a regular console.log(obj) > reload page > switch to a terminal (🔁 repeat with console.log(obj.property...) flow.

Give it a try, you'll "enjoy" it.

I will be using a fresh [`create-next-app`](https://github.com/zeit/create-next-app) example to demonstrate how it works.

# Step one: create your Next.js debugging demo application

<small>_You can [skip to step two](#step-two-configure-nextjs-to-start-in-debug-mode) if you already have a Next.js application_</small>

**in a terminal:**
```bash
> npx create-next-app
✔ What is your project named? … demo-nextjs-debugging
# wait...
> cd create-next-app
```

# Step two: configure Next.js to start in debug mode

Edit the file `package.json` and change this part:

```json
  "scripts": {
-   "dev": "next",
+   "dev": "NODE_OPTIONS='--inspect' next",
  }
```

If you have a different way of launching Next.js, just make sure that `NODE_OPTIONS='--inspect'` is always right before the `next` command.

I like to change the default `dev` command so that anytime I am in developer mode, I can start a debugging session in one shortcut (more on that in step four).

_Be aware that using `NODE_OPTIONS='--inspect' npm run dev` or `NODE_OPTIONS='--inspect' yarn run dev` won't work. This would try to start multiple debuggers on the same port: one for the npm/yarn process and one for Next.js. You would then get an error like `Starting inspector on 127.0.0.1:9229 failed: address already in use` in your console_.

`NODE_OPTIONS` is a [standard Node.js flag](https://nodejs.org/api/cli.html#cli_node_options_options).

# Step three: launch your application

**in a terminal:**
```bash
> yarn dev
yarn run v1.22.0
$ NODE_OPTIONS='--inspect' next dev
Debugger listening on ws://127.0.0.1:9229/6bd49cb3-e640-4d76-ad88-86480e167df7
For help, see: https://nodejs.org/en/docs/inspector
[ wait ]  starting the development server ...
[ info ]  waiting on http://localhost:3000 ...
[ ready ] compiled successfully - ready on http://localhost:3000
```

# Step four: connect your debugging inspector

This is a convoluted title but it just means connecting either VS Code debugging feature or Chrome DevTools to your Next.js application.

## VS Code

<small>_You can also [skip to the chosen solution](#vscode-solution)._<small>

There are multiple ways to connect the VS Code inspector to your Next.js application running in debug mode. All of that is explained in VS Code gigantic [Node.js debugging documentation page](https://code.visualstudio.com/docs/nodejs/nodejs-debugging).

You can either:
1. Configure VS Code to actually start your Next.js application for you and connect to its debugger. Frankly, this is not my favorite solution because usually all developer environments are already using some sort of process manager like [node-foreman](https://github.com/strongloop/node-foreman), ❤️ [overmind](https://github.com/DarthSim/overmind), [docker-compose](https://docs.docker.com/compose/), [heroku local](https://devcenter.heroku.com/articles/heroku-local#run-your-app-locally-using-the-heroku-local-command-line-tool-start-your-app-locally), [nodemon](https://github.com/remy/nodemon). So... No!
2. Start your Next.js application from within the internal terminal of VS Code so it detects it. Same as 1., I don't use the internal VS Code terminal, I have a side terminal already.
3. **Configure VS Code so that it connects to your already started Next.js application**. ✅ That's what I like.

---
<a name="vscode-solution"></a>

Here's how to do it:

Create **.vscode/launch.json** at the root of your project:
```json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      "name": "Launch Program",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "port": 9229
    }
  ]
}
```

Save it. Now hit `F5` on your keyboard or go click on "Run and Debug (F5)" in the 🐞 debugging panel of VS Code. You should get this:

![Example of a debugging session in VS Code](https://dev-to-uploads.s3.amazonaws.com/i/p66g868ngwrylwqo3eu9.png)

As you can see, you now have the full VS Code inspector connected to your Next.js application. It even shows the console output.

Now, whenever you think "Hmm, I wonder what's not working, what does this variable really holds". Just hit F5 in VS Code, trigger the underlying code (page refresh, click..) and enjoy a nice debugging experience!

### Bonus: If your Next.js code is not at the root of your workspace

If your Next.js project is not at the root of your VSCode workspace, then you need to add:

**.vscode/launch.json**
```json
{
  // ...
  "configurations": [
    {        
      // ...
      "sourceMapPathOverrides": {
        "webpack:///./*": "${workspaceRoot}/subfolder/*",
      }
    }
  ]
}
```

Thanks [ubermensh](https://dev.to/ubermensh) for the tip!

## Chrome DevTools

If you prefer to debug your Next.js application using the regular Chrome DevTools, all you have to do now is open a new tab in Chrome with the url being: `chrome://inspect`.

You'll see this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/walps033jzju00lh7cwr.png)

Click on "inspect" and the Chrome DevTools are now connected to your Next.js application.

# Step five: actually debug your application

Now all you have to do is setup breakpoints in your application. Either by adding the `debugger;` keyword anywhere in your code or by clicking on the left of a line to turn it into a breakpoint in VS Code editor or Chrome.

Whenever you do so and the underlying code runs (page load, page click, api call...) then a debugging UI will popup.

How to use VS Code or Chrome debugging tools is better explained by their own docs:
- [VS Code Node.js debugging: Breakpoints](https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_breakpoints)
- [Get Started with Debugging JavaScript in Chrome DevTools](https://developers.google.com/web/tools/chrome-devtools/javascript)

---

🔚 That's it!

🙏 Thank you for reading.

Did you enjoy this post? Any advice as for Next.js or Node.js debugging? Add a thank you note or advice in the comments and I'll reply :)

Click below to share this post:

{% twitter 1235144272900431873 %}