nrwl / nx

Smart Monorepos · Fast CI
https://nx.dev
MIT License
23.7k stars 2.37k forks source link

Add debug capabilities for nx next apps #4154

Open estyh opened 3 years ago

estyh commented 3 years ago

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.

dsebastien commented 3 years ago

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:

> writer-plan@0.0.0 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! writer-plan@0.0.0 start:writer-plan: `NODE_OPTIONS='--inspect=9229' nx serve`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the writer-plan@0.0.0 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! writer-plan@0.0.0 start: `npm run start`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the writer-plan@0.0.0 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..

itaywol commented 3 years ago

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

techgerm commented 3 years ago

@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?

github-actions[bot] commented 3 years ago

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! 🙏

kirjai commented 3 years ago

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!

yuriy-eleks commented 3 years ago

@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 !

oscyp commented 3 years ago

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

juristr commented 3 years ago

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

https://youtu.be/VHkb26kHjgA

jeffreyschultz commented 3 years ago

@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?

kirjai commented 3 years ago

@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?

jeffreyschultz commented 3 years ago

@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/"
    }
  ]
}
kriswuollett commented 3 years ago

@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:

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.

deeeed commented 2 years ago

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

yuriy-eleks commented 2 years ago

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

alfonsodev commented 2 years ago

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 ?

pokey commented 2 years ago

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

adamwdennis commented 2 years ago

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!

aarifkhamdi commented 2 years ago

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

bosycom commented 2 years ago

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:

  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!

KamalAman commented 1 year ago

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

TCotton commented 1 year ago

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

darkopetrovic commented 1 year ago

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" 
      }
}
Falven commented 1 year ago

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.

MartinDavi commented 1 year ago

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

tgirotto commented 1 year ago

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>",
        },
    ]
}
JoshElias commented 1 year ago

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

Falven commented 1 year ago

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

yacineblr commented 1 year ago

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 ?

nbolton commented 9 months ago
      "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"
    }
FrozenPandaz commented 7 months ago

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.

vespertilian commented 7 months ago
{
  "name": "next",
  "$schema": "../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "next",
  "projectType": "application",
  "tags": [],
  "// targets": "to see all targets run: nx show project next --web",
  "targets": {
    "debug": {
      "executor": "nx:run-commands",
      "options": {
        "cwd": "next",
        "command": "NODE_OPTIONS='--inspect' next dev"
      }
    },

This work for me in webstorm. NX 18.2.2 to debug next server code next 14.1.4

emarancient commented 4 months ago

https://github.com/nrwl/nx/issues/4154#issuecomment-1946247372 This one was working for me until our application updated to NX 19.3.0, now doesn't work again.

azmi-plavaga commented 1 month ago
{
  "name": "next",
  "$schema": "../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "next",
  "projectType": "application",
  "tags": [],
  "// targets": "to see all targets run: nx show project next --web",
  "targets": {
    "debug": {
      "executor": "nx:run-commands",
      "options": {
        "cwd": "next",
        "command": "NODE_OPTIONS='--inspect' next dev"
      }
    },

This work for me in webstorm. NX 18.2.2 to debug next server code next 14.1.4

Works in VSCode with NX: "19.7.4" and next: "14.2.12" as well. Thanks @vespertilian