Repository: vercel/next.js
Pull request: Handle pnpm-workspace.yaml while searching for monorepo root

## What?

In order for Next.js to know where the root of the project (i.e. monorepo) is we have a heuristic for searching for the root by looking upwards from the application's directory trying to find the package manager lockfiles. This works really well and in practice you rarely have to provide the root directory. In some cases, e.g. when you're creating a monorepo based on an existing repository you might forget to delete the previous repository lockfile. E.g. in #74731 that was the cause for the issue. While having that lockfile in the repo doesn't do anything it does affect the project root heuristic because that unused lockfile is matched on the filesystem and is higher up than the actual root (in the application directory).

While looking at the reproduction in #74731 I realized we can consider `pnpm-workspace.yaml` first before matching the lockfiles. Still need to verify if we need a separate findup call for that or if it will recursively look up per item first.

Fixes #74731


<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to understand the PR)
- When linking to a Slack thread, you might want to share details of the conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Changed files:
filename: packages/next/src/lib/find-root.ts
patch: @@ -2,7 +2,21 @@ import { dirname } from 'path'
 import findUp from 'next/dist/compiled/find-up'
 import * as Log from '../build/output/log'
 
-export function findRootLockFile(cwd: string) {
+function findWorkRoot(cwd: string) {
+  // Find-up evaluates the list of files at each level.
+  // For pnpm-workspace.yaml we first want to look up before searching for lockfiles as those can be included in the application directory by accident.
+  const pnpmWorkspaceFile = findUp.sync(
+    'pnpm-workspace.yaml',
+
+    {
+      cwd,
+    }
+  )
+
+  if (pnpmWorkspaceFile) {
+    return pnpmWorkspaceFile
+  }
+
   return findUp.sync(
     [
       'pnpm-lock.yaml',
@@ -21,7 +35,7 @@ export function findRootDirAndLockFiles(cwd: string): {
   lockFiles: string[]
   rootDir: string
 } {
-  const lockFile = findRootLockFile(cwd)
+  const lockFile = findWorkRoot(cwd)
   if (!lockFile)
     return {
       lockFiles: [],
@@ -37,7 +51,7 @@ export function findRootDirAndLockFiles(cwd: string): {
     // dirname('/')==='/' so if we happen to reach the FS root (as might happen in a container we need to quit to avoid looping forever
     if (parentDir === currentDir) break
 
-    const newLockFile = findRootLockFile(parentDir)
+    const newLockFile = findWorkRoot(parentDir)
 
     if (!newLockFile) break
 

filename: test/e2e/app-dir/pnpm-workspace-root/pnpm-workspace-root.test.ts
patch: @@ -0,0 +1,68 @@
+import { nextTestSetup } from 'e2e-utils'
+
+describe('pnpm-workspace-root', () => {
+  const { next, skipped } = nextTestSetup({
+    files: {
+      'app/layout.tsx': `
+        import { ReactNode } from 'react'
+        export default function Root({ children }: { children: ReactNode }) {
+          return (
+            <html>
+              <body>{children}</body>
+            </html>
+          )
+        }
+      `,
+      'app/page.tsx': `
+        import { message } from '../../shared/utils'
+        export default function Page() {
+          return <p>{message}</p>
+        }
+      `,
+      // Write a package-lock.json (npm lockfile, ignored by pnpm) to the application directory
+      // directory to create the scenario where multiple "lockfiles" exist.
+      'package-lock.json': JSON.stringify({
+        name: 'parent-workspace',
+        version: '1.0.0',
+        lockfileVersion: 3,
+      }),
+      // Write pnpm-workspace.yaml in the same parent directory.
+      // This file should be prioritized over lockfiles when determining root.
+      // Note: pnpm-workspace.yaml will be detected by pnpm, but since we also
+      // include a proper package.json, it should work correctly.
+      '../pnpm-workspace.yaml': 'packages:\n  - "test"\n',
+      '../package.json': JSON.stringify({
+        name: 'workspace-root',
+        private: true,
+      }),
+      // Shared file outside of the test directory (in the workspace root)
+      // This tests that files outside the Next.js app directory but inside
+      // the pnpm workspace root can be imported correctly.
+      '../shared/utils.ts': `
+        export const message = 'hello world'
+      `,
+    },
+    // So that parent files don't leave the isolated testDir
+    subDir: 'test',
+    skipDeployment: true,
+  })
+
+  if (skipped) {
+    return
+  }
+
+  it('should detect root directory from pnpm-workspace.yaml and allow imports from outside app dir', async () => {
+    // The app should start successfully when pnpm-workspace.yaml is present
+    // and correctly resolve imports from outside the Next.js app directory
+    // (e.g., from ../shared/utils.ts which is in the workspace root)
+    const browser = await next.browser('/')
+    expect(await browser.elementByCss('p').text()).toBe('hello world')
+  })
+
+  it('should not have multiple lockfiles warning when pnpm-workspace.yaml is present', async () => {
+    // When pnpm-workspace.yaml is found, it should be used as the root indicator
+    // and we shouldn't see the "multiple lockfiles" warning since pnpm-workspace.yaml
+    // is prioritized and acts as the definitive workspace root marker
+    expect(next.cliOutput).not.toMatch(/We detected multiple lockfiles/)
+  })
+})