Mon Oct 04 2021
Debugging a Next.js project in Visual Studio Code
Nextjs is the most popular of the «JAMStack» site generators. Next combines build time rendering with serverside rendering and some «in-between» features like server rendering and caching on request.
Since Next is such a versatile tool, it isn't always straight forward how to debug your code. So, in this aricle I'll walk through setting up debugging both for the server rendering part and the client (in the browser).
Setting up debugging for Visual Studio Code
The first thing you'll need to do is to do it to tell webpack how to generate the correct devtoolModuleFilenameTemplate
. This is done by editing the next.config.js
file.
Your next.config.js
file should look something like this.
/** @type {import('next').NextConfig} */
const webpack = require("webpack");
module.exports = {
// ... your config
// This is for debugging to work
webpack(config) {
config.output = config.output || {};
config.output.devtoolModuleFilenameTemplate = function (info) {
return "file:///" + encodeURI(info.absoluteResourcePath);
};
return config;
},
};
The next step is to add a debug script to your package.json
file. This script will be used later in the launch config. You can name this script whatever you want, I'm using «debug» for this example.
{
"name": "...",
"version": "1.0.0",
"scripts": {
"dev": "next dev",
"debug": "set NODE_OPTIONS=--inspect&&next",
"build": "next build",
"start": "next start"
},
"dependencies": {},
"devDependencies": {}
}
Now let's move on to the launch config. Create a new launch confor from the VSCode debug menu and add the following:
Notice that we are reffering to the «debug» npm script in the «Next: Node» config.
{
"version": "0.2.0",
"configurations": [
{
"name": "Next: Edge",
"request": "launch",
"type": "pwa-msedge",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}"
},
{
"type": "node",
"request": "launch",
"name": "Next: Node",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "debug"],
"port": 9229,
"console": "integratedTerminal"
}
],
"compounds": [
{
"name": "Next: Full",
"configurations": ["Next: Node", "Next: Edge"]
}
]
}
There are two configs here and one compound config letting you start both at the same time.
- «Next: Edge» - This will launch the Edge browser (this requires the Edge plugin for VSCode). You can also use the older Chrome debugger for this if you want.
- «Next: Node» - Start this to debug any server side stuff, such as logic inside «getStaticProps» and so on.
How to debug
This part is pretty straight forward. Just set breakpoints within VSCode and trigger them. Note that if you are debugging functions like «getStaticPaths» and others that run at launch, it might be a good idea to set the breakpoints before you trigger the launch config.
That's it. Happy debugging.