nx icon indicating copy to clipboard operation
nx copied to clipboard

Add debug capabilities for nx next apps

Open estyh opened this issue 4 years ago • 16 comments

Description

I would like to be able to debug my next app from inside nx, preferably using vscode. The app has imports from react libs within nx.

I can't figure out how to do this... there is no documentation about debugging at all (at least, not that I can find).

Using a mish-mash of how-to's, I was able to configure breakpoints for either my libs, or for the next app, but not for both.

estyh avatar Nov 26 '20 12:11 estyh

Same problem here, I've tried a few things, but couldn't get debugging to work for my Next.js app. Thread: https://nrwlcommunity.slack.com/archives/CMFKWPU6Q/p1611558322095900

I've tried adding NODE_OPTIONS='--inspect=9229' before nx serve, but it fails with address already in use, even though that port is really not in use when I launch the command:

Scripts:

"start": "npm run start:writer-plan",
"start:writer-plan": "NODE_OPTIONS='--inspect=9229' nx serve",

Command output:

> [email protected] start:writer-plan /home/sebastien/wks/writerPlan
> NODE_OPTIONS='--inspect=9229' nx serve

Debugger listening on ws://127.0.0.1:9229/d5ae279c-932c-4a9f-b754-776835174fc1
For help, see: https://nodejs.org/en/docs/inspector
Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db

> nx run writer-plan:serve 
Starting inspector on 127.0.0.1:9229 failed: address already in use
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start:writer-plan: `NODE_OPTIONS='--inspect=9229' nx serve`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start:writer-plan script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/sebastien/.npm/_logs/2021-01-25T08_29_45_729Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `npm run start`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/sebastien/.npm/_logs/2021-01-25T08_29_45_761Z-debug.log

If I watch the ports, I can see that the socket is opened at some point, then it crashes. As if the script tried to open the same port twice; obviously failing the second time.

Note that I also can't seem to get rid of the error about browserlist not being up to date; but I suppose that it's not related..

dsebastien avatar Jan 25 '21 08:01 dsebastien

Also facing the same issue, when using NODE_OPTIONS the inspector starts at the nx.js command and not the next instance. the next schematic should have debugging preferences.

Update a workaround for setting NODE_OPTIONS specifically for the Next instance would be placing a .env file in the application folder including the NODE_OPTIONS=--inspect=0.0.0.0:9229 as written in this guide

itaywol avatar Jan 30 '21 17:01 itaywol

@itaywol that definitely worked in regards to starting the debugging after running nx run [app_name]:serve but I'm still not able to debug getServerSideProps. Did you have any luck with that?

techgerm avatar Feb 02 '21 04:02 techgerm

This issue has been automatically marked as stale because it hasn't had any recent activity. It will be closed in 14 days if no further activity occurs. If we missed this issue please reply to keep it active. Thanks for being a part of the Nx community! 🙏

github-actions[bot] avatar Mar 29 '21 14:03 github-actions[bot]

we're actually looking at implementing this via an --inspect flag that you can pass into nx serve. but in the meantime, the clever workaround from this comment is the way to go!

kirjai avatar Apr 16 '21 13:04 kirjai

@itaywol provided workaround doesn't work if you have imports from lib, because it can be run via nx run <app name>:serve

Seems it critical issue, cause application cannot be debugged !

yuriy-eleks avatar May 06 '21 17:05 yuriy-eleks

Anyone? How does your configuration file look like? In my case, I can attach the debugger, but breakpoints are not hit (they are grey in VS Code).

oscyp avatar May 19 '21 18:05 oscyp

This seems to work for now until we have a more DX friendly option

https://youtu.be/VHkb26kHjgA

juristr avatar May 21 '21 15:05 juristr

@kirjai Any official updates on this functionality? Is there at least a description of how this can be accomplished, and perhaps someone from the community can submit a pull request?

jeffreyschultz avatar Jun 29 '21 00:06 jeffreyschultz

@jeffreyschultz unfortunately we hit a bit of a blocker with implementing this. it's been a while since i've looked into it, but from what i remember, original thinking was that we'd just fork a child process and launch nextjs from that child process, passing in the --inspect flag. but we have some configuration options that would need to be passed into this child process that can't be passed via a CLI we still plan to revisit this functionality, but it's just not a quick-win that we thought it might be.

i hope at least the workarounds in this thread work for you?

kirjai avatar Jun 29 '21 12:06 kirjai

@jeffreyschultz unfortunately we hit a bit of a blocker with implementing this. it's been a while since i've looked into it, but from what i remember, original thinking was that we'd just fork a child process and launch nextjs from that child process, passing in the --inspect flag. but we have some configuration options that would need to be passed into this child process that can't be passed via a CLI we still plan to revisit this functionality, but it's just not a quick-win that we thought it might be.

i hope at least the workarounds in this thread work for you?

I was able to get debugging working using some tweaks to the launch.json file.

{
  "version": "0.2.0",
  "resolveSourceMapLocations": ["${workspaceFolder}/**", "!**/node_modules/**"],
  "configurations": [
    {
      "name": "client-portal-webapp",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "npm",
      "runtimeArgs": [
        "run",
        "nx",
        "run",
        "client-portal-webapp:serve",
        "-r",
        "ts-node/register",
        "-r",
        "tsconfig-paths/register"
      ],
      "protocol": "inspector",
      "outputCapture": "std",
      "internalConsoleOptions": "openOnSessionStart",
      "console": "internalConsole",
      "env": {
        "TS_NODE_IGNORE": "false",
        "TS_NODE_PROJECT": "${workspaceFolder}/apps/client/portal-webapp/tsconfig.json"
      },
      "cwd": "${workspaceFolder}/apps/client/portal-webapp/"
    }
  ]
}

jeffreyschultz avatar Jun 29 '21 16:06 jeffreyschultz

@jeffreyschultz your launch.json was helpful, thanks! Not sure how it can be improved further, but for this issue in general the problems I'm still having, some of which may be VSCode/Typescript/NX in general are:

  • VSCode can't bind the breakpoints (they're initially a grey circle), until the code is executed in that file -- I assume because it finally gets compiled.
  • Once the code is run, I somehow then have breakpoints that I don't expect, like in the middle of a line or a parameter variable.
  • Stepping doesn't work as expected since in this example step in or step over causes the function to return somewhere instead of stopping on line 39 (successful case of credentials check):
NX NextJS Debugging

Is there some aspect of source map not working for me properly? My workspace has NX at a src/js relative path, so I've updated your example with changes to the first item in resolveSourceMapLocation, TS_NODE_PROJECT, and cwd. I also don't have a subdirectory for apps. So my NextJS app is simply at src/js/apps/APP where APP is my actual app name (simple lowercase).

Currently I can just lay down a bunch of breakpoints in an area and at least one will be hit so I can inspect variables which is helpful, but would be good to get proper debugging working.

kriswuollett avatar Oct 06 '21 16:10 kriswuollett

I have tried the different workrounds with the env file or the custom launch settings but I still can't debug inside getStaticProps... All the breakpoints are unbound.

Someone must have found a way? It really becomes a deal breaker otherwise...

deeeed avatar Jan 29 '22 10:01 deeeed

I have tried the different workrounds with the env file or the custom launch settings but I still can't debug inside getStaticProps... All the breakpoints are unbound.

Someone must have found a way? It really becomes a deal breaker otherwise...

We moved from nx with next

yuriy-eleks avatar Jan 29 '22 10:01 yuriy-eleks

we still plan to revisit this functionality, but it's just not a quick-win that we thought it might be. @kirjai is there any news on this ?

alfonsodev avatar Jul 21 '22 11:07 alfonsodev

Fwiw, here is what worked for me (in the configurations section of my .vscode/launch.json):

		{
			"name": "foo-bar client-side",
			"type": "chrome",
			"request": "launch",
			"url": "http://localhost:4200",
			"webRoot": "${workspaceFolder}",
			"sourceMapPathOverrides": {
				"webpack://_N_E/*": "${webRoot}/apps/foo-bar/*",
				"webpack://_N_E/libs/*": "${webRoot}/libs/*",
				"webpack://_N_E/node_modules/*": "${webRoot}/node_modules/*"
			}
		}

Replace foo-bar with the app name you're debugging. This SO answer was helpful

pokey avatar Aug 09 '22 14:08 pokey

Fwiw, here is what worked for me (in the configurations section of my .vscode/launch.json):

		{
			"name": "foo-bar client-side",
			"type": "chrome",
			"request": "launch",
			"url": "http://localhost:4200",
			"webRoot": "${workspaceFolder}",
			"sourceMapPathOverrides": {
				"webpack://_N_E/*": "${webRoot}/apps/foo-bar/*",
				"webpack://_N_E/libs/*": "${webRoot}/libs/*",
				"webpack://_N_E/node_modules/*": "${webRoot}/node_modules/*"
			}
		}

Replace foo-bar with the app name you're debugging. This SO answer was helpful

After much trial & error, this worked for me! Thanks!

adamwdennis avatar Sep 26 '22 12:09 adamwdennis

This helped me https://github.com/nrwl/nx/issues/1248#issuecomment-483449715

aarifkhamdi avatar Oct 29 '22 18:10 aarifkhamdi

I was (finally) able to successfully set breakpoints in my Jetbrains IDE to debug my NextJS app within my Nx workspace, without changing any Nx config files. I tested it on Windows, but it should work for Linux too:

In your Jetbrains IDE, create a Run/Debug Configuration of type Node.js with these parameters:

  1. Node parameters: --inspect=0 Setting it to 0 will create random ports to avoid address already in use error
  2. Working directory: The path of your nx workspace root (the one containing /apps and /libs etc.), e.g. C:\code\my-project
  3. JavaScript file: node_modules\@nrwl\cli\bin\nx.js
  4. Application parameters: run my-project:serve:development

Run the task (Shift + F10). Do not “Debug the task", otherwise you get the address already in use error.

What it does:

  • It will start up two debug sessions, each listening on a different random port, e.g. ws://127.0.0.1:49876 and ws://127.0.0.1:49877 (the reason why this creates two debug sessions is even mentioned on the official NextJs doc page)
  • It will start your nextJS development server on http://localhost:4200 (default port used for NextJS in Nx)
  1. Create another Run/Debug configuration, this time of type Attach to Node.js/Chrome
  2. In Port Enter the port number of the second debug session, in our case above 49877
  3. Debug the task (Shift + F9)

Done. Breakpoints should now be recognized by Jetbrains IDE.

The downside is of course, that you have to adjust the ports anytime you start a new debug session. Apparently, debugging JS/TS in 2022 is still not easy or straightforward, unfortunately. Please let me know if you found any easier way to achieve the same thing. I hope this helps you. It still took many tries for me to make it work. Happy coding!

bosycom avatar Nov 03 '22 16:11 bosycom

Using a Debug Terminal and adding a debugger; statement in code worked to debug SSR. This issue really hinders the developer experience using NX :)

KamalAman avatar Jan 02 '23 14:01 KamalAman

is there still no easy solution for this? that's a shame.

TCotton avatar Feb 12 '23 08:02 TCotton

Easiest solution for me in VSCode so far:

Add NODE_OPTIONS=--inspect in .env file.

Debug server side:

{
      "name": "Attach server",
      "port": 9229,
      "request": "attach",
      "skipFiles": ["<node_internals>/**"],
      "type": "node",
      // magic line to fix Unbound breakpoints:
      "cwd": "${workspaceFolder}/apps/<yourapp>",
},

Debug client side:

{
      "name": "Launch client",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:4200",
      "webRoot": "${workspaceFolder}",
      "sourceMaps": true,
      "sourceMapPathOverrides": {
	 "webpack://_N_E/*": "${webRoot}/apps/<yourapp>/*",
	 "webpack://_N_E/libs/*": "${webRoot}/libs/*",
	 "webpack://_N_E/node_modules/*": "${webRoot}/node_modules/*"
	}
    },

Run nx serve <yourapp>. Start either Attach server, Launch client or both.


Debug full-stack in one command:

{
      "name": "Full Stack",
      "type": "node-terminal",
      "request": "launch",
      "command": "cd ../../ && nx run <yourapp>:serve",
      "cwd": "${workspaceFolder}/apps/<yourapp>",
      "serverReadyAction": {
        "action": "startDebugging",
        "name": "Launch client",
        "pattern": "on http://localhost:4200" 
      }
}

darkopetrovic avatar Mar 19 '23 03:03 darkopetrovic

Here's my solution, extending @darkopetrovic's above:

"version": "0.2.0",
  "inputs": [
    {
      "id": "selectProject",
      "type": "pickString",
      "description": "Select a project to debug",
      "options": ["admin-portal", "sso"]
    }
  ],
  "configurations": [
    {
      "name": "Next.js: debug client-side",
      "type": "msedge",
      "request": "launch",
      "url": "http://localhost:3000",
      "webRoot": "${workspaceFolder}/apps/${input:selectProject}"
    },
    {
      "name": "Next.js: debug server-side",
      "type": "node-terminal",
      "request": "launch",
      "command": "cd ../../ && nx serve ${input:selectProject}",
      "cwd": "${workspaceFolder}/apps/${input:selectProject}"
    },
    {
      "name": "Next.js: debug full stack",
      "type": "node-terminal",
      "request": "launch",
      "command": "cd ../../ && nx serve ${input:selectProject}",
      "cwd": "${workspaceFolder}/apps/${input:selectProject}",
      "serverReadyAction": {
        "pattern": "started server on .+, url: (https?://.+)",
        "uriFormat": "%s",
        "action": "debugWithEdge",
        "webRoot": "${workspaceFolder}/apps/${input:selectProject}"
      }
    }

I'm trying to see if I can get it to work with pnpx next commands instead to support console ninja and other external functionality.

Falven avatar Mar 25 '23 16:03 Falven

@bosycom your solution worked for me, thank you very much - what a pain though.

MartinDavi avatar Apr 22 '23 11:04 MartinDavi

Here is what worked for me:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "<app-name>",
            "runtimeExecutable": "nx",
            "runtimeArgs": [
                "serve",
                "<app-name>"
            ],
            "console": "integratedTerminal",
            "outFiles": [
                "${workspaceFolder}/**/*.js",
                "!**/node_modules/**"
            ],
            "cwd": "${workspaceFolder}/apps/<app-name>",
        },
    ]
}

tgirotto avatar Apr 26 '23 14:04 tgirotto

Fwiw, here is what worked for me (in the configurations section of my .vscode/launch.json):

		{
			"name": "foo-bar client-side",
			"type": "chrome",
			"request": "launch",
			"url": "http://localhost:4200",
			"webRoot": "${workspaceFolder}",
			"sourceMapPathOverrides": {
				"webpack://_N_E/*": "${webRoot}/apps/foo-bar/*",
				"webpack://_N_E/libs/*": "${webRoot}/libs/*",
				"webpack://_N_E/node_modules/*": "${webRoot}/node_modules/*"
			}
		}

Replace foo-bar with the app name you're debugging. This SO answer was helpful

I feel like this should be in the @nx/next docs along with https://github.com/nrwl/nx/issues/4154#issuecomment-870757625

JoshElias avatar Sep 24 '23 04:09 JoshElias

There's yet another bug with getting the debugger to work with NX/Next. This time it's on the vscode side. Using the nightly debugger extension fixes it. Instructions here: https://github.com/microsoft/vscode-js-debug#nightly-extension

Falven avatar Oct 07 '23 03:10 Falven

Voici ce qui a fonctionné pour moi:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "<app-name>",
            "runtimeExecutable": "nx",
            "runtimeArgs": [
                "serve",
                "<app-name>"
            ],
            "console": "integratedTerminal",
            "outFiles": [
                "${workspaceFolder}/**/*.js",
                "!**/node_modules/**"
            ],
            "cwd": "${workspaceFolder}/apps/<app-name>",
        },
    ]
}

It worked for me, but how do I use .env please ?

yacineblr avatar Oct 30 '23 10:10 yacineblr

      "command": "cd ../../ && nx serve ${input:selectProject}",
      "cwd": "${workspaceFolder}/apps/${input:selectProject}"

This cwd/cd trick did it for me. Now my breakpoints work. How strange!

image

Before (broken):

    {
      "name": "foo-bar",
      "type": "node-terminal",
      "request": "launch",
      "cwd": "${workspaceFolder}",
      "command": "npx nx serve -bar"
    }

After (works):

    {
      "name": "foo-bar",
      "type": "node-terminal",
      "request": "launch",
      "cwd": "${workspaceFolder}/apps/-bar",
      "command": "cd ../..; npx nx serve -bar"
    }

nbolton avatar Feb 15 '24 14:02 nbolton

Can someone check if this is easier in a new Nx + Next.js workspace? We recently reworked how we execute the Next Dev Server from the root of the project. Perhaps that makes debugging via VS Code easier? It should work just as documented on the Next.js webiste.

FrozenPandaz avatar Apr 02 '24 18:04 FrozenPandaz