nextjs - 💡(How to fix) Fix Turbopack fails to include hoisted monorepo dependencies in Vercel serverless bundles (valibot, @typeschema/valibot) [1 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
vercel/next.js#89205Fetched 2026-04-08 02:03:07
View on GitHub
Comments
1
Participants
2
Timeline
11
Reactions
0
Timeline (top)
labeled ×7closed ×1commented ×1issue_type_added ×1

When deploying a Next.js 15+ application (using Turbopack by default) in a monorepo to Vercel, dependencies installed in the root node_modules are not included in serverless function bundles, causing runtime errors.

This specifically affects:

  • valibot - ESM validation library
  • @typeschema/valibot - TypeSchema adapter
  • Potentially other ESM-first packages in monorepo contexts

Error Message

Error: Cannot find package 'valibot' imported from /var/task/dist/apps/wl/.next/server/chunks/7957.js

Root Cause

Next.js's file tracer (used during Vercel deployment) doesn't properly resolve dependencies when:

  1. Turbopack is used for bundling (default in Next.js 15+)
  2. Dependencies are hoisted to root node_modules (monorepo standard)
  3. Packages are ESM-first (like valibot)

The file tracer stops at the app boundary and doesn't traverse up to ../../node_modules/.

Fix Action

Fix / Workaround

Current Workaround

This workaround:

  • ✅ Makes deployment work
  • ❌ Should not be necessary
  • ❌ Must be updated for every affected package
  • ❌ Not discoverable (no error message suggests this fix)
  • ❌ Brittle (may break with package updates)

With Turbopack (Requires Workaround)

# Default in Next.js 15+
next build
vercel --prod
# ❌ Fails unless outputFileTracingIncludes is manually configured

Code Example

Error: Cannot find package 'valibot' imported from /var/task/dist/apps/wl/.next/server/chunks/7957.js

---

turbopack: true

---

monorepo-root/
├── package.json          # Root workspace config
├── pnpm-workspace.yaml   # pnpm workspace definition
├── node_modules/
│   ├── valibot/          # ← Installed here (hoisted)
│   └── @typeschema/
│       └── valibot/      # ← Installed here (hoisted)
└── apps/
    └── wl/               # Next.js app
        ├── package.json
        ├── next.config.js
        └── src/
            └── app/
                └── api/
                    └── route.ts  # ← Imports valibot

---

# pnpm-workspace.yaml
packages:
  - 'apps/*'

---

// Root package.json
{
  "name": "monorepo-root",
  "private": true,
  "dependencies": {
    "valibot": "^0.42.1",
    "@typeschema/valibot": "^0.1.0"
  }
}

---

// apps/wl/package.json
{
  "name": "wl-app",
  "dependencies": {
    "next": "15.1.2",
    "react": "18.3.1",
    "react-dom": "18.3.1",
    "valibot": "^0.42.1"
  },
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}

---

// apps/wl/src/app/api/test/route.ts
import { object, string, parse } from 'valibot';

const schema = object({
  name: string(),
});

export async function POST(request: Request) {
  const data = await request.json();
  const validated = parse(schema, data);
  return Response.json({ success: true, data: validated });
}

---

cd apps/wl
pnpm build  # ✅ Works locally
pnpm start  # ✅ Works locally

# Deploy to Vercel
vercel --prod  # ❌ Fails with "Cannot find package 'valibot'"

---

// apps/wl/next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    outputFileTracingIncludes: {
      '/api/**/*': [
        '../../node_modules/valibot/**/*',
        '../../node_modules/@typeschema/valibot/**/*',
      ],
      '/*': [
        '../../node_modules/valibot/**/*',
        '../../node_modules/@typeschema/valibot/**/*',
      ],
    },
  },
};

module.exports = nextConfig;

---

# No special configuration needed
next build --webpack
vercel --prod
# ✅ Works perfectly - all dependencies included automatically

---

# Default in Next.js 15+
next build
vercel --prod
# ❌ Fails unless outputFileTracingIncludes is manually configured

---

resolve: {
  modules: [
    path.resolve(__dirname, 'node_modules'),
    path.resolve(__dirname, '../../node_modules'),  // ← Checks parent
    'node_modules',
  ],
}

---

{
  "monorepo": "pnpm workspaces",
  "structure": "apps/wl (Next.js app in subdirectory)",
  "dependencies": "hoisted to root node_modules",
  "deployment": "Vercel",
  "nextjs": "15.1.2",
  "turbopack": "enabled by default",
  "node": "20.x"
}

---

Building with Turbopack...
Compiled successfully
...
Error: Cannot find package 'valibot' imported from /var/task/dist/apps/wl/.next/server/chunks/7957.js

---

// Pseudo-code for what file tracing should do
function traceModules(entryPoint, depth = 0) {
  const imports = parseImports(entryPoint);
  
  for (const importPath of imports) {
    // Current behavior: only checks app-level node_modules
    const resolved = resolve(importPath, { paths: ['./node_modules'] });
    
    // Suggested: walk up directory tree like Webpack
    const resolved = resolve(importPath, { 
      paths: [
        './node_modules',
        '../node_modules',
        '../../node_modules',  // ← Add parent directory checks
        // ... continue up to project root
      ]
    });
    
    include(resolved);
  }
}

---

Error: Cannot find package 'valibot' imported from /var/task/dist/apps/wl/.next/server/chunks/7957.js

---

turbopack: true

---

### Provide environment information

Operating System:
  Platform: linux/darwin/win32
  Arch: x64/arm64
Binaries:
  Node: 18.x / 20.x
  npm: 10.x
  Yarn: N/A
  pnpm: 9.x
Relevant Packages:
  next: 15.1.2 (or your version)
  eslint-config-next: 15.1.2
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.3.3
Next.js Config:
  output: N/A
  turbopack: enabled (default in Next.js 15+)
RAW_BUFFERClick to expand / collapse

Link to the code that reproduces this issue

github.com

To Reproduce

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Which area(s) are affected? (Select all that apply)

  • Turbopack (with --turbo or Next.js 15+)
  • Module resolution
  • Monorepo (pnpm/npm/yarn workspaces)
  • Vercel deployment

Which stage(s) are affected? (Select all that apply)

  • next dev (local)
  • next build (local)
  • next start (local)
  • Vercel (Deployed)

Additional context

Deployment platform: Vercel
Monorepo setup: pnpm workspaces (or npm/yarn workspaces)
Package manager: pnpm 9.x


Description

When deploying a Next.js 15+ application (using Turbopack by default) in a monorepo to Vercel, dependencies installed in the root node_modules are not included in serverless function bundles, causing runtime errors.

This specifically affects:

  • valibot - ESM validation library
  • @typeschema/valibot - TypeSchema adapter
  • Potentially other ESM-first packages in monorepo contexts

The Issue

What happens:

  1. ✅ Local development works (next dev --turbopack)
  2. ✅ Local production build works (next build)
  3. ✅ Local production server works (next start)
  4. Vercel deployment fails with module resolution error

Error on Vercel:

Error: Cannot find package 'valibot' imported from /var/task/dist/apps/wl/.next/server/chunks/7957.js

Build metadata from Sentry:

turbopack: true

Expected Behavior

Turbopack should automatically include all resolved dependencies (including those hoisted to root node_modules in monorepos) in the serverless function bundle, just like Webpack does.

No manual configuration should be required.

Actual Behavior

Turbopack's file tracing does not properly traverse up to ../../node_modules/ in monorepo structures, causing hoisted dependencies to be excluded from the Vercel serverless function bundle.


Reproduction

Minimal Repository Structure

monorepo-root/
├── package.json          # Root workspace config
├── pnpm-workspace.yaml   # pnpm workspace definition
├── node_modules/
│   ├── valibot/          # ← Installed here (hoisted)
│   └── @typeschema/
│       └── valibot/      # ← Installed here (hoisted)
└── apps/
    └── wl/               # Next.js app
        ├── package.json
        ├── next.config.js
        └── src/
            └── app/
                └── api/
                    └── route.ts  # ← Imports valibot

Reproduction Steps

  1. Create monorepo with workspaces:
# pnpm-workspace.yaml
packages:
  - 'apps/*'
// Root package.json
{
  "name": "monorepo-root",
  "private": true,
  "dependencies": {
    "valibot": "^0.42.1",
    "@typeschema/valibot": "^0.1.0"
  }
}
  1. Create Next.js app:
// apps/wl/package.json
{
  "name": "wl-app",
  "dependencies": {
    "next": "15.1.2",
    "react": "18.3.1",
    "react-dom": "18.3.1",
    "valibot": "^0.42.1"
  },
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}
  1. Use valibot in API route:
// apps/wl/src/app/api/test/route.ts
import { object, string, parse } from 'valibot';

const schema = object({
  name: string(),
});

export async function POST(request: Request) {
  const data = await request.json();
  const validated = parse(schema, data);
  return Response.json({ success: true, data: validated });
}
  1. Build and deploy:
cd apps/wl
pnpm build  # ✅ Works locally
pnpm start  # ✅ Works locally

# Deploy to Vercel
vercel --prod  # ❌ Fails with "Cannot find package 'valibot'"

Link to Reproduction Repository

[Optional - you can create a minimal repo if needed]


Current Workaround

Adding experimental.outputFileTracingIncludes to manually specify the packages:

// apps/wl/next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    outputFileTracingIncludes: {
      '/api/**/*': [
        '../../node_modules/valibot/**/*',
        '../../node_modules/@typeschema/valibot/**/*',
      ],
      '/*': [
        '../../node_modules/valibot/**/*',
        '../../node_modules/@typeschema/valibot/**/*',
      ],
    },
  },
};

module.exports = nextConfig;

This workaround:

  • ✅ Makes deployment work
  • ❌ Should not be necessary
  • ❌ Must be updated for every affected package
  • ❌ Not discoverable (no error message suggests this fix)
  • ❌ Brittle (may break with package updates)

Comparison: Webpack vs Turbopack

With Webpack (Works Correctly)

# No special configuration needed
next build --webpack
vercel --prod
# ✅ Works perfectly - all dependencies included automatically

With Turbopack (Requires Workaround)

# Default in Next.js 15+
next build
vercel --prod
# ❌ Fails unless outputFileTracingIncludes is manually configured

This proves the issue is specific to Turbopack's file tracing/bundling, not the package or monorepo setup.


Technical Analysis

Root Cause

Next.js's file tracer (used during Vercel deployment) doesn't properly resolve dependencies when:

  1. Turbopack is used for bundling (default in Next.js 15+)
  2. Dependencies are hoisted to root node_modules (monorepo standard)
  3. Packages are ESM-first (like valibot)

The file tracer stops at the app boundary and doesn't traverse up to ../../node_modules/.

Why Webpack Works

Webpack's resolver explicitly checks parent directories:

resolve: {
  modules: [
    path.resolve(__dirname, 'node_modules'),
    path.resolve(__dirname, '../../node_modules'),  // ← Checks parent
    'node_modules',
  ],
}

Turbopack's file tracing doesn't have equivalent logic for production bundles on Vercel.


Impact

Affected Scenarios

  • Monorepo + Turbopack + Vercel - Fails
  • Monorepo + Webpack + Vercel - Works
  • Single-repo + Turbopack + Vercel - Works
  • Monorepo + Turbopack + Local - Works

Affected Packages

Not limited to valibot - this affects any ESM package in hoisted monorepo node_modules:

  • valibot
  • @typeschema/*
  • zod (in some configurations)
  • @prisma/client (in some monorepo setups)
  • Other ESM-first validation/schema libraries

Scale of Impact

  • Affects all Next.js 15+ users in monorepos deploying to Vercel
  • No clear error message or documentation
  • Workaround is not intuitive or discoverable
  • Creates production-specific bugs (works locally, fails deployed)

Expected Resolution

Turbopack's file tracing should:

  1. Automatically detect hoisted dependencies in monorepo contexts
  2. Include them in serverless bundles without manual configuration
  3. Match Webpack's behavior for dependency resolution
  4. Work the same locally and on Vercel

No outputFileTracingIncludes workaround should be necessary.


Additional Information

Related Issues

  • #71923 - Tailwind CSS fails in Safari with Turbopack (similar bundling issues)
  • #64514 - Monorepo dependencies not resolved correctly
  • #58290 - outputFileTracingIncludes workaround discussion

Environment Details

{
  "monorepo": "pnpm workspaces",
  "structure": "apps/wl (Next.js app in subdirectory)",
  "dependencies": "hoisted to root node_modules",
  "deployment": "Vercel",
  "nextjs": "15.1.2",
  "turbopack": "enabled by default",
  "node": "20.x"
}

Build Logs

[If you have relevant build logs, include them here]

Building with Turbopack...
✓ Compiled successfully
...
Error: Cannot find package 'valibot' imported from /var/task/dist/apps/wl/.next/server/chunks/7957.js

Suggested Fix

The Next.js file tracer should:

// Pseudo-code for what file tracing should do
function traceModules(entryPoint, depth = 0) {
  const imports = parseImports(entryPoint);
  
  for (const importPath of imports) {
    // Current behavior: only checks app-level node_modules
    const resolved = resolve(importPath, { paths: ['./node_modules'] });
    
    // Suggested: walk up directory tree like Webpack
    const resolved = resolve(importPath, { 
      paths: [
        './node_modules',
        '../node_modules',
        '../../node_modules',  // ← Add parent directory checks
        // ... continue up to project root
      ]
    });
    
    include(resolved);
  }
}

Or better yet, use the already-resolved module paths from Turbopack's bundling instead of re-tracing with different resolution logic.


Conclusion

This is a regression from Webpack's behavior and creates a poor developer experience:

  • Works in development ✅
  • Works in local production ✅
  • Fails in deployed production ❌
  • No helpful error message
  • Requires undocumented workaround

For Next.js to be truly "Turbopack by default," it should handle monorepo dependencies as seamlessly as Webpack does.

Thank you for looking into this!

Current vs. Expected behavior

Error on Vercel:

Error: Cannot find package 'valibot' imported from /var/task/dist/apps/wl/.next/server/chunks/7957.js

Build metadata from Sentry:

turbopack: true

Expected Behavior

Turbopack should automatically include all resolved dependencies (including those hoisted to root node_modules in monorepos) in the serverless function bundle, just like Webpack does.

No manual configuration should be required.

Actual Behavior

Turbopack's file tracing does not properly traverse up to ../../node_modules/ in monorepo structures, causing hoisted dependencies to be excluded from the Vercel serverless function bundle.


Provide environment information

### Provide environment information

Operating System:
  Platform: linux/darwin/win32
  Arch: x64/arm64
Binaries:
  Node: 18.x / 20.x
  npm: 10.x
  Yarn: N/A
  pnpm: 9.x
Relevant Packages:
  next: 15.1.2 (or your version)
  eslint-config-next: 15.1.2
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.3.3
Next.js Config:
  output: N/A
  turbopack: enabled (default in Next.js 15+)

Which area(s) are affected? (Select all that apply)

Module Resolution

Which stage(s) are affected? (Select all that apply)

next build (local)

Additional context

No response

extent analysis

TL;DR

The most likely fix for the issue is to update Next.js's file tracer to automatically detect and include hoisted dependencies in monorepo contexts, similar to Webpack's behavior.

Guidance

  1. Verify the issue: Confirm that the issue occurs only when using Turbopack with a monorepo setup and deploying to Vercel.
  2. Check the file tracer: Investigate the file tracer used by Next.js to see if it can be updated to properly resolve dependencies in monorepo contexts.
  3. Compare with Webpack: Study how Webpack resolves dependencies in similar scenarios to identify potential improvements for Turbopack.
  4. Test with a minimal repro: Create a minimal reproduction of the issue to test potential fixes and verify that they resolve the problem.
  5. Consider a temporary workaround: If a fix is not immediately available, consider using the experimental.outputFileTracingIncludes option as a temporary workaround, although this should not be necessary in the long term.

Example

// Pseudo-code for what file tracing should do
function traceModules(entryPoint, depth = 0) {
  const imports = parseImports(entryPoint);
  
  for (const importPath of imports) {
    // Current behavior: only checks app-level node_modules
    const resolved = resolve(importPath, { paths: ['./node_modules'] });
    
    // Suggested: walk up directory tree like Webpack
    const resolved = resolve(importPath, { 
      paths: [
        './node_modules',
        '../node_modules',
        '../../node_modules',  // ← Add parent directory checks
        // ... continue up to project root
      ]
    });
    
    include(resolved);
  }
}

Notes

  • The issue seems to be specific to Turbopack's file tracing and bundling in monorepo contexts.
  • Webpack's behavior in similar scenarios provides a useful comparison for identifying potential fixes.
  • A temporary workaround using experimental.outputFileTracingIncludes may be necessary until a proper fix is implemented.

Recommendation

Apply the workaround using experimental.outputFileTracingIncludes until a fix is available that updates Next.js's file tracer to properly handle monorepo dependencies with Turbopack.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING