发布

  • fix(nextjs): use cached project graph in withNx (#35475)

    frostbyte_neo 发布于 2026-04-28 20:42:20 +00:00

    Current Behavior

    @nx/next/plugins/with-nx.ts calls createProjectGraphAsync() from
    inside next.config.js evaluation. This has two negative effects:

    1. Sandbox violations. Calling createProjectGraphAsync inside the
      build re-runs every registered Nx plugin's createNodesV2. For example,
      on nx-dev:next:build this generates 562 unexpected reads — including
      548 files from packages/nx/dist/**/*.js (Nx core internals loaded by
      the graph machinery) plus sibling project files like
      nx-dev/nx-dev-e2e/playwright.config.ts, spec files, and
      eslint.config.mjs files that are read by @nx/playwright/plugin and
      @nx/eslint/plugin while inferring targets. None of these are real
      input dependencies of the Next.js build — they are an implementation
      detail of graph creation.

    2. Daemon socket leak (workaround in #34518). The same call also
      opens a daemon client socket that keeps the Node event loop alive. PR
      #34518 patched this with resetDaemonClient: true after Jest started
      hanging in #32880. The socket exists only because we are talking to the
      daemon to (re)build the graph at all.

    Both problems share a root cause: graph creation is being run inside the
    build, when the graph has already been built and cached by the Nx task
    runner before next build ever starts.

    Expected Behavior

    withNx reads the already-cached graph instead of rebuilding it.

    This matches the pattern used by @nx/webpack
    (packages/webpack/src/plugins/nx-webpack-plugin/lib/normalize-options.ts)
    and @nx/rspack
    (packages/rspack/src/plugins/utils/plugins/normalize-options.ts), both
    of which call readCachedProjectGraph() with the comment "Since this
    is invoked by the executor, the graph has already been created and
    cached."

    The early-return guard already in withNx (no NX_TASK_TARGET_TARGET
    env var) ensures we only reach the graph-reading branch when running
    inside an Nx task, which is exactly when the cached graph is guaranteed
    to exist.

    This change:

    • Eliminates the 562 sandbox violations on nx-dev:next:build (verified
      locally by patching node_modules/@nx/next/plugins/with-nx.js and
      re-running the build).
    • Removes the need for resetDaemonClient: true since no daemon
      connection is opened in the first place — also obviating the original
      Jest hang.
    • Speeds up next build slightly by skipping a full graph re-creation
      pass.

    Related Issue(s)

    Follow-up to #34518 / #32880 — fixes the underlying cause that the
    daemon-reset workaround was treating.

    下载附件