Debugging Next.js apps in Visual Studio Code

5 July 2020

We're all guilty at some point of debugging our code with print statements / console.log. There's nothing inherently wrong with that, however sometimes it's nice to use a fully fledged debugger, especially when investigating a particularly tricky bug that involves multiple variables and nested logic. This is a quick guide on how to setup debugging for Next.js apps in Visual Studio Code:

You will need to create a .vscode folder in the root of your project and add into it two files named launch.json and tasks.json (You may already have these files in your project).

launch.json

In launch.json we will declare how to run Next.js in dev mode (npm run dev) through the debugger:

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch Next.js app",
      "request": "launch",
      "runtimeArgs": ["run", "dev"],
      "runtimeExecutable": "npm",
      "skipFiles": ["<node_internals>/**"],
      "type": "node",
      "preLaunchTask": "load-local-env-variables"
    }
  ]
}
.vscode/launch.json

The runtimeExecutable and runtimeArgs fields instruct Visual Studio Code to attach the debugger to the npm command (`npm run dev`). While the type field is set to "node" it doesn't stop up from debugging both React component and API endpoints. The preLaunchTask field is optional, however it's often handy to run a few commands to setup your environment before the debugger starts. In my case, my Next.js app uses environment variables which I've stored locally in a .env.local file. "load-local-env-variables" is an arbitrary name I've given to a task to source the environment variables but name you choose can be whatever you like. One caveat is that your name must match a label value of a task in the tasks.json file.

tasks.json

We use tasks.json to define any actions we want run before or after debugging. My tasks.json file would look like this:

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "label": "load-local-env-variables",
      "type": "shell",
      "command": "source ./.env.local"
    }
  ]
}
.vscode/tasks.json

I've only defined one task though you can add as many as you like. Notice that the label of the task ("load-local-env-variables") exactly matches the value of the preLaunchTask field in the launch.json file.

Run the debugger and start debugging!

Now it's simply a matter of running the debugger via the 'Run' sidebar is visual studio code:

Logs will start to display in 'Debug Console' of VS Code and once Next.js has loaded you can open the URL in your browser (http://localhost:3000 by default). Add a few breakpoints in your code and everything should be working.