diff --git a/packages/next/plugins/with-nx.ts b/packages/next/plugins/with-nx.ts index 555c57be61d02..5d4d3a4aa3bed 100644 --- a/packages/next/plugins/with-nx.ts +++ b/packages/next/plugins/with-nx.ts @@ -112,12 +112,12 @@ function withNx( const { PHASE_PRODUCTION_SERVER, PHASE_DEVELOPMENT_SERVER } = await import( 'next/constants' ); - if ( - PHASE_PRODUCTION_SERVER === phase || - !process.env.NX_TASK_TARGET_TARGET - ) { - // If we are running an already built production server, just return the configuration. - // NOTE: Avoid any `require(...)` or `import(...)` statements here. Development dependencies are not available at production runtime. + // Two scenarios where we want to skip graph creation: + // 1. Running production server means the build is already done so we just need to start the Next.js server. + // 2. During graph creation (i.e. create nodes), we won't have a graph to read, and it is not needed anyway since it's a build-time concern. + // + // NOTE: Avoid any `require(...)` or `import(...)` statements here. Development dependencies are not available at production runtime. + if (PHASE_PRODUCTION_SERVER === phase || global.NX_GRAPH_CREATION) { const { nx, ...validNextConfig } = _nextConfig; return { distDir: '.next', @@ -126,21 +126,19 @@ function withNx( } else { const { createProjectGraphAsync, - readCachedProjectGraph, joinPathFragments, offsetFromRoot, workspaceRoot, } = require('@nx/devkit'); - let graph = readCachedProjectGraph(); - if (!graph) { - try { - graph = await createProjectGraphAsync(); - } catch (e) { - throw new Error( - 'Could not create project graph. Please ensure that your workspace is valid.' - ); - } + let graph: ProjectGraph; + try { + graph = await createProjectGraphAsync(); + } catch (e) { + throw new Error( + 'Could not create project graph. Please ensure that your workspace is valid.', + { cause: e } + ); } const originalTarget = {