2

I'm trying to debug a Next.js app with a custom server which I normally run with a dev Yarn script that executes node server.js.

VSCode includes a Node.js debugging extension and this guide, which I've followed. I created a new Yarn script called dev:debug that runs node --inspect server.js, and the following configuration in launch.json:

{ "type": "node", "request": "launch", "name": "Debug via Yarn", "runtimeExecutable": "yarn", "runtimeArgs": ["dev:debug"], "port": 9229 } 

However some breakpoints in modules imported by server.js are skipped and I'm not sure why. Other breakpoints in Next components do work when I load pages in my web app. Any ideas?

1 Answer 1

2

OK! Here's what's happening (and I'm posting all this to SO because I couldn't find the answer online):

When you build a Next.js app, you're writing BOTH the server app (node), AND the server-side web app (next), which are separate things! Additionally, you're also building a client-side app (React) on top of that. (If you're used to other platforms like PHP or Python web apps that use servers like the built-in ones, Apache, or NginX, this isn't obvious!)

Running node --inspect server.js tells the debugger to load the server and THEN start debugging your web app ONLY ("user code").

Solution: node CLI has a special --inspect-brk option to use when you also want to debug the code of the server itself! Yep, the solution is 4 more characters (-brk).

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

4 Comments

I found this out not so long ago. It may cause problem for anyone who tries to share a singleton service between custom server code and your next.js code (e.g. getServerSideProps) because it will be two different singleton instances. So you can only share stateless modules.
Thanks @dannyjee. I'm not doing much Node anymore so I'm not sure what that means but is there a better solution for those cases?
When you setup custom server, you'll do something like: const handler = nextApp.getRequestHandler()(req, res); You can add a property to req object like so: req.messageQueue = new MessageQueue(connectionString); which will allow the next.js code to access the same instance of the MessageQueue class.
Sorry, I don't see how that relates to my original question on VSCode debugger and breakpoints.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.