6

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?

5
  • I'd recommend a read through Next.js Debugging documentation. Commented Oct 10, 2021 at 13:40
  • @juliomalves did that before asking, no information about what I asked Commented Oct 11, 2021 at 5:32
  • Have you tried using the launch.json that's there, running the debug server-side configuration, and setting a breakpoint on your API route? Commented Oct 11, 2021 at 6:43
  • yes, I have done that Commented Oct 11, 2021 at 12:41
  • I don't believe you can set breakpoints on NextJs API calls. The documentation seems to think that users want to review the 'compiled code' when they say Click inspect under your application to open a separate DevTools window, then go to the Sources tab which does not seem useful for debugging server side code at specific points of execution. Commented Oct 28, 2021 at 15:23

5 Answers 5

2

I was having the same problem clicking on the sidebar in VSCode to place the red dots.

The good news is that there is still a way. In VSCode, rather than clicking to set the red dot on the line you want, just write debugger on that line instead. Not sure why it would work one way but not the other - maybe there is one more tweak that could make clicking to set dots actually work? So far this is as good as it gets for me with the api routes:

npm run dev

Now attach the debugger with the following launch.json. (My next.js project was in a subfolder of my workspace folder, so my own config needed to reflect that. The config below assumes the Next.js project root is the same as the $workspaceFolder.)

{
    "name": "Attach",
    "port": 9229,
    "request": "attach",
    "webRoot": "${workspaceFolder}", // mine had another subfolder here
    "cwd": "${workspaceFolder}",     // and here
    "skipFiles": [
        "<node_internals>/**"
    ],
    "type": "pwa-node"
},

Now in VSCode, wherever you want the breakpoint:

handler.get(async (req, res) => {
  debugger;

  console.log....
});

Should end up with something like this

Sign up to request clarification or add additional context in comments.

1 Comment

it works, thanks. wierd why breakpoints do not work, but adding debugger works.
2

I have the same problem, but resolved by two steps:

  1. Add a line in VSCode settings.json: "debug.javascript.usePreview": false

  2. 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.

Update

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:

  1. If you start your server manually in VSCODE terminal by type "npm run dev", VSCODE will automatically find the debugging ports and you will be fine.
  2. If you start your server outside of VSCODE from a terminal, and then use 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.
  3. If you use 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

Comments

2

In July 2024 on VSC 1.91.1, you can follow the steps below to run and debug NextJS/NodeJS/ExpressJS:

1 - Click on: enter image description here

2 - Then click on enter image description here

Choose the script you want to run from the list. All the scripts in the package.json should be listed. I tested with "Run Script: dev" enter image description here

3 - Finally click on run enter image description here

Comments

1

I know it might be too late to reply but it can be useful to others. I just followed what was specified here https://nextjs.org/docs/advanced-features/debugging and it worked fine. Copy the part relevant to debugging full stack and remember to change the directory if your code is in as subfolder, for example, this worked for me

 {
            "name": "Next.js: debug full stack",
            "type": "node-terminal",
            "request": "launch",
            "command": "npm run dev",
            "cwd": "${workspaceFolder}/client",
            "serverReadyAction": {
                "pattern": "started server on .+, url: (https?://.+)",
                "uriFormat": "%s",
                "action": "debugWithChrome"
            }
        }

Comments

0

This issue has been ongoing for more than 2 years now and it amazes me how Next team didn't bother to update their docs. They had the answers all along.

47561

   {
      "name": "Next.js: debug full stack",
      "request": "launch",
      "type": "node",
      "runtimeArgs": ["--inspect"],
      "program": "${workspaceFolder}/node_modules/.bin/next",
      "skipFiles": ["<node_internals>/**"],
      "serverReadyAction": {
        "action": "debugWithEdge",
        "killOnServerStop": true,
        "webRoot": "${workspaceFolder}",
        "pattern": "- Local:.+(https?://.+)",
        "uriFormat": "%s"
      }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.