Currently, I have to manually find which file(api endpoint) I to set breakpoint in /api folder in VSCode.
I have the following launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach to application",
"skipFiles": ["<node_internals>/**"],
"port": 9229
}
]
}
Is there a way to automatically stop or set breakpoint whenever there is an incoming request to that specific Nextjs Api Route?
For example, let's say I have an /api/data.tsx :
import { NextApiRequest, NextApiResponse } from 'next';
import { StatusCodes } from 'http-status-codes';
import getConfig from 'next/config';
export default async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
console.log('do some logging');
res.status(StatusCodes.OK).json({message: 'Good job buddy!'});
}
And want to stop on console.log on every incoming request. How can I do it?
I have the same problem, but resolved by two steps:
Add a line in VSCode settings.json: "debug.javascript.usePreview": false
Don't use NODE_OPTIONS="--inspect"
Then you may still see unbound breakpoint, but run the app and set the breakpoint again, it will be red and works well.
Sometimes, I still have problem with setting breakpoint on API, so I took a few hours to figure out what's the real problem. Finally I found the issue:
Because when you run a Nextjs app, Node will first run next script, then next script will spawn a child process which is your own code. Nextjs also automatically set NODE_OPTIONS=--inspect when you use dev mode, but it use different port number and the number changes automatically. The KEY POINT is: The Next script and the child process will have different debugging port number. That is the reason that you sometimes can't set breakpoints.
There are some scenarios:
attach, VSCODE will only attach one port, usually only attached to
Nextjs script. That's why you can't set breakpoint in you own code.launch method to start server in launch.json. Then same
problem will happened like No.2, You can't set your breakpoint.There is a simple way to solve the problem: Either start server from VSCODE internal terminal or in launch.json, add:
"autoAttachChildProcesses": true,
then you can start debugging by hit F5 and everything going well.
{
"name": "Next.js: debug full stack",
"type": "node-terminal",
"request": "launch",
"command": "npm run dev",
"serverReadyAction": {
"pattern": "started server on .+, url: (https?://.+)",
"uriFormat": "%s",
"action": "debugWithChrome"
},
"autoAttachChildProcesses": true,
}
You don't need to add NODE_OPTION='--inspect', neither "debug.javascript.usePreview": false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With