AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Turbopack: Missing Optional PeerDependencies Fail Module Resolution (Webpack Ignores Them)

Turbopack in Next.js 16 does not respect the `peerDependenciesMeta` field when a peer dependency is marked as optional. As a result, packages that declare optional peer dependencies (common for plugin-style libraries) cause builds to fail with 'Module not found' even when the missing dependency is only referenced from dead code and never executed. Webpack handles this correctly via its OptionalPeerDependencyResolverPlugin, but Turbopack lacks an equivalent, leading to a regression for projects migrating to Turbopack.

highConfidence 85%Next.jsAffected V16.0.0Affected V16.4.0-Canary.4

Origin Analysis

Turbopack's resolver does not check whether a failed resolution request corresponds to an optional peer dependency of the importing package. Webpack explicitly ignores such unresolvable optional peers, but Turbopack treats the missing module as a hard error. The underlying design flaw is the absence of a resolver hook or configuration in Turbopack to handle optional peer dependencies, which are a standard npm feature.
1. Clone https://github.com/scs0209/nextjs-optional-peer-turbopack-repro 2. Run `pnpm install` 3. Run `pnpm build` (uses Turbopack by default) 4. Observe build failure with `Module not found: Can't resolve 'foo'` 5. Optionally run `pnpm exec next build --webpack` to see the expected success

Fixing Code Block

Edge Case Audit

This fix may cause a silent failure if an optional peer is actually required at runtime but missing—the code path that uses it would receive an empty module and likely throw a runtime error, which is still better than a build failure but may be unexpected. Additionally, the resolution fallback adds a file I/O lookup on every failed resolve, potentially impacting performance in large projects. Rollback is straightforward: remove the added fallback code and revert to the original resolver. In concurrent or multi-threaded builds, ensure the package.json reads are cached or use a shared filesystem abstraction to avoid race conditions or excessive overhead.

Ecosystem Topology