This article's content
Debug NextJS with Nx in Jetbrains

Creating a debug session for NextJS within a Nx workspace is not an easy straightforward task as this NX issue shows (after two years the issue is still open). Solutions are mentioned for VSCode, but none for Jetbrains IDE. This article describes how to enable Server-Side NextJS debugging in a Nx managed monorepo using Breakpoints in a Jetbrains IDE. Tested on Jetbrains 2022.2.3 in Windows, might work in Linux as well.

Problem

The official NextJS debugging doc page states:

The same applies to running a debug session with Nx.

Solution

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

  • Name: Start NextJS Nx debugger or any other title
  • Node interpreter: Select any entry that points to your node.exe
  • Node parameters: --inspect=0
  • Working directory: The path of your nx workspace root (the one containing /apps and /libs etc.), e.g. C:\code\my-project
  • JavaScript file: node_modules\@nrwl\cli\bin\nx.js
  • Application parameters: run my-project:serve:development

Run the task (Shift + F10). Do not “Debug the task”, otherwise you will get

Starting inspector on 127.0.0.1:49352 failed: address already in use

This will:

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

Testing it

To test it, you can set breakpoints like in the following example and reload the login page in your browser.

import { LoginPage } from "@portreb/ui";

export async function getServerSideProps(context: any) {
  console.log("set a breakpoint here");
  return { props: { yes: true } };
}

export default function () {
  console.log("set a breakpoint here too");
  return <LoginPage />
}

About Author

Mathias Bothe To my job profile

I am Mathias from Heidelberg, Germany. I am a passionate IT freelancer with 15+ years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I create Bosycom and initiated several software projects.