next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Turbopack generates external module references with hashes that don't match installed packages when node_modules structure differs

Open yWilliamLima opened this issue 11 months ago • 33 comments

Link to the code that reproduces this issue

https://github.com/Aluisio/test-styled-components

To Reproduce

  1. Create a Next.js 16.1.1+ project with OpenTelemetry instrumentation
  2. Add instrumentation.ts file that imports @opentelemetry/auto-instrumentations-node
  3. Build the project in a CI/CD environment (e.g., GitHub Actions) using pnpm install --frozen-lockfile followed by next build
  4. Create a tar.gz archive excluding node_modules directory
  5. Extract the tar.gz in a different environment
  6. Run pnpm install to install dependencies
  7. Run next start to start the production server

Current vs. Expected behavior

Expected Behavior

The application should start successfully, loading the instrumentation hook without errors.

Current Behavior

The application fails to start with the following error:

Error: An error occurred while loading instrumentation hook: Failed to load external module require-in-the-middle-a99415fa67232f7f: Error: Cannot find module 'require-in-the-middle-a99415fa67232f7f'
Require stack:
- /path/to/.next/server/chunks/[root-of-the-server]__39a9a9e1._.js
- /path/to/.next/server/chunks/[turbopack]_runtime.js
- /path/to/.next/server/instrumentation.js

The Turbopack bundler generates external module references with hashes (e.g., require-in-the-middle-a99415fa67232f7f) based on the node_modules structure during the build. When dependencies are reinstalled in a different environment, the node_modules structure may differ (especially with pnpm's symlink/hoisting behavior), causing the hash to not match the actual installed package.

Workaround

Using --webpack flag in the build script resolves the issue:

{
  "scripts": {
    "build": "next build --webpack"
  }
}

However, this defeats the purpose of using Turbopack as the default bundler in Next.js 16.

Provide environment information

**Operating System:**

- Platform: linux
- Arch: x64
- Version: Ubuntu (GitHub Actions runner)

**Binaries:**

- Node: 24.11.1
- pnpm: 10.25.0

**Relevant Packages:**

- next: 16.1.1
- react: 19.2.3
- react-dom: 19.2.3
- @opentelemetry/auto-instrumentations-node: 0.67.3
- require-in-the-middle: 8.0.1
- import-in-the-middle: 2.0.1

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

Output

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

Other (Deployed)

Additional context

Next.js Config:

/** @type {import('next').NextConfig} */
const nextConfig = {};

export default nextConfig;

Note: The issue occurs even with serverExternalPackages configured:

const nextConfig = {
  serverExternalPackages: [
    "require-in-the-middle",
    "import-in-the-middle",
    "@opentelemetry/auto-instrumentations-node",
    // ... other OpenTelemetry packages
  ],
};

Why this happens

  1. Local development works: When building and running locally, the same node_modules structure is used for both build and runtime, so the hashes match.

  2. CI/CD fails: The build is created with node_modules structure A (from CI environment), generating hashes based on that structure. When the tar.gz is extracted and dependencies are reinstalled locally, the node_modules structure may be different (structure B), causing hash mismatches.

  3. Root cause: Turbopack generates external module references with content-based hashes that depend on the node_modules directory structure. This is problematic when:

    • Using pnpm (which uses symlinks and hoisting)
    • Building in one environment and running in another
    • Reinstalling dependencies after extracting a build artifact

Impact

This issue affects:

  • Projects using OpenTelemetry instrumentation (common in production applications)
  • CI/CD pipelines that build artifacts without node_modules and reinstall dependencies later
  • Projects using pnpm as package manager
  • Any project that needs to build in one environment and run in another

Testing

Tested against:

  • Next.js 16.1.1 (current)
  • Next.js 16.0.0 (same issue)
  • Next.js 15.x with Webpack (works correctly)

The issue appears to be introduced when Turbopack became the default bundler for production builds in Next.js 16.

yWilliamLima avatar Dec 23 '25 23:12 yWilliamLima

getting same error, any update on this

Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote 👍 on the issue description or subscribe to the issue for updates. Thanks!

jitendra-bhandure avatar Dec 24 '25 09:12 jitendra-bhandure

Based on my comment from https://github.com/vercel/next.js/issues/87686#issuecomment-3690396866

Can you try with the following config in your next.config.ts file? CC: @yWilliamLima, @jitendra-bhandure

  transpilePackages: ["import-in-the-middle", "require-in-the-middle"],

I'm also running the @opentelemetry/ packages in my project and this fixed it for me. I didn't need to configure any serverExternalPackages array, though - it worked with just transpilePackages.

arolariu avatar Dec 24 '25 21:12 arolariu

is there any way of opting out from making the node module dependencies part of the build? We should be able to have a clean build and install the dependencies separately. This idea of embedding packages as part of the build with a hash is also causing problem to us and it looks like a really unconventional pattern.

pascual-cano-allhuman avatar Dec 25 '25 07:12 pascual-cano-allhuman

[Error: ENOENT: no such file or directory, open '[root]/public/.next/node_modules/@hookform/resolvers-7a17b6f70f9232cf'] { errno: -2, code: 'ENOENT', syscall: 'open', path: '[root]/public/.next/node_modules/@hookform/resolvers-7a17b6f70f9232cf' } Error: ENOENT: no such file or directory, open '[root]/public/.next/node_modules/@hookform/resolvers-7a17b6f70f9232cf'

I am also having this error on ci when upgrading to 16.1.1 whereas on 16.0.10 everything was fine Also one difference I noticed is in 16.1.1 in .next folder we have node_modules whereas 16.0.10 doesn't have node_modules

hasankhurshid29 avatar Dec 25 '25 20:12 hasankhurshid29

@pascual-cano-allhuman I believe you can force packages to symlink to node_modules instead of bundling them into .next with serverExternalPackages since Next v16.1. Don't think that this is possible for the entire node_modules though.

taletski avatar Dec 26 '25 12:12 taletski

@yWilliamLima, as discussed in #87686, the issue seems to be broken symlinks for require-in-the-middle and its downstream dependencies (e.g. @opentelemetry/*).

Since you’re using tar, symlinks inside .next should be preserved. This makes me suspect that the symlinks point to a different location than where the packages are actually installed in the runtime container.

Could you please share the directory structure for both the build container and the runtime container? Specifically, it would be helpful to see:

  • Where @opentelemetry/* is installed in each container
  • Where .next/node_modules/@opentelemetry/* symlinks point to at runtime container

taletski avatar Dec 26 '25 12:12 taletski

@taletski In our project we are not using Server Components, we are entirely in the Pages Router side. How comes that the newest version is still bundling dependencies? Shouldn't be able to opt out of bundling with a single config flag without keeping the list of exceptions manually? This behaviour seems related to turbopack in production. The dependencies are not bundled if we add the --webpack modifier.

pascual-cano-allhuman avatar Dec 27 '25 20:12 pascual-cano-allhuman

@pascual-cano-allhuman I agree that having a flag for full opt out might be beneficial in some cases. Happy to discuss in a separate feature request issue to have more room for it, to have more chances to convince maintainers and to keep the scope narrow here.

taletski avatar Dec 28 '25 12:12 taletski

I created a discussion about being able to opt out from external packages completely: #87891

pascual-cano-allhuman avatar Dec 29 '25 08:12 pascual-cano-allhuman

Since you’re using tar, symlinks inside .next should be preserved. This makes me suspect that the symlinks point to a different location than where the packages are actually installed in the runtime container.

I followed this hint in our project and found that symlinks in .next/node_modules where pointing to nowhere

had to fix node_modules COPY target in our Dockerfile and everything is back to normal

In our case had to add extra ../../ to preserve node_modules "relative" distance from .next/node_modules and avoid recreating symlinks

karlismelderis-mckinsey avatar Jan 05 '26 12:01 karlismelderis-mckinsey

The issue was actually the symbolic links created in .next/node_modules. Adjusting the compression command solved the problem. Thanks!

yWilliamLima avatar Jan 05 '26 20:01 yWilliamLima

So is this issue resolved? It's unfortunate that your setup broke here, but https://github.com/vercel/next.js/pull/86375 describes the benefits of this approach.

mischnic avatar Jan 08 '26 12:01 mischnic

I was also experiencing this issue since 16.1 while building in a monorepo and using turbo prune. Here is how I fixed it:

I have a basic Turborepo monorepo:

apps/
  myapp/
packages/
  leftpad/
pnpm-lock.yaml

In my CI/CD the workflow looks like:

turbo prune --scope=myapp --out-dir=pruned/myapp
pushd pruned/myapp/apps/myapp
pnpm install
pnpm build
popd

I noticed the below warning while building which clued me into what was happening. Because my pruned monorepo was inside of my main monorepo, when Next.js was building, the transitive dependencies in .next/node_modules were symlinking to PROJECT_DIR/node_modules instead of PROJECT_DIR/pruned/myapp/node_modules and when I copied only the pruned monorepo after building, of course the symlinks were no longer pointing to the correct place.

⚠ Warning: Next.js inferred your workspace root, but it may not be correct.
 We detected multiple lockfiles and selected the directory of PROJECT_DIR/pnpm-lock.yaml as the root directory.
 To silence this warning, set `turbopack.root` in your Next.js config, or consider removing one of the lockfiles if it's not needed.
   See https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#root-directory for more information.
 Detected additional lockfiles: 
   * PROJECT_DIR/pruned/myapp/pnpm-lock.yaml

Following the advice of the warning above, I added turbopack.root to my next.config.ts and after that, transitive dependencies in .next/node_modules correctly symlinked to PROJECT_DIR/pruned/myapp/node_modules after building:

let nextConfig: NextConfig = {
  turbopack: {
    root: path.join(__dirname, "../.."),
  },
}

msheakoski avatar Jan 18 '26 02:01 msheakoski

I have the same monorepo structure as @msheakoski in my project

apps/
  myapp/
packages/
  leftpad/

locally with npm run dev everything works fine. In our Dockerfile then we had the issue and the symlinks were not copied and if they would they would have been wrong.

So we are doing the following

COPY app/.next/standalone/app ./
COPY app/.next/standalone/node_modules ./node_modules
COPY app/.next/static ./.next/static
COPY app/public ./public

as you may notice we didnt copy the app/.next/node_modules. So to have the symlinks eventually we do the following:

RUN if [ -d ".next/node_modules" ]; then \
        cd node_modules && \
        for link in ../.next/node_modules/*; do \
            if [ -L "$link" ]; then \
                hashed_name=$(basename "$link"); \
                pkg_name=$(echo "$hashed_name" | sed 's/-[0-9a-f]*$//'); \
                if [ -d "$pkg_name" ] && [ ! -e "$hashed_name" ]; then \
                    echo "Creating symlink: $hashed_name -> $pkg_name"; \
                    ln -sf "$pkg_name" "$hashed_name"; \
                fi; \
            fi; \
        done; \
    fi

this basically lists symlinks in .next/node_modules and creates then those symlinks in the node_modules folder so that the hashed packages point to the original packages.
import-in-the-middle-ac114f323ad7e863 -> import-in-the-middle

flodev avatar Jan 22 '26 10:01 flodev

I have the same monorepo structure as @msheakoski in my project

apps/
  myapp/
packages/
  leftpad/

locally with npm run dev everything works fine. In our Dockerfile then we had the issue and the symlinks were not copied and if they would they would have been wrong.

So we are doing the following

COPY app/.next/standalone/app ./
COPY app/.next/standalone/node_modules ./node_modules
COPY app/.next/static ./.next/static
COPY app/public ./public

as you may notice we didnt copy the app/.next/node_modules. So to have the symlinks eventually we do the following:

RUN if [ -d ".next/node_modules" ]; then \
        cd node_modules && \
        for link in ../.next/node_modules/*; do \
            if [ -L "$link" ]; then \
                hashed_name=$(basename "$link"); \
                pkg_name=$(echo "$hashed_name" | sed 's/-[0-9a-f]*$//'); \
                if [ -d "$pkg_name" ] && [ ! -e "$hashed_name" ]; then \
                    echo "Creating symlink: $hashed_name -> $pkg_name"; \
                    ln -sf "$pkg_name" "$hashed_name"; \
                fi; \
            fi; \
        done; \
    fi

this basically lists symlinks in .next/node_modules and creates then those symlinks in the node_modules folder so that the hashed packages point to the original packages.
import-in-the-middle-ac114f323ad7e863 -> import-in-the-middle

This seems like an awful developer experience...

Either we're not understanding properly this change or the documentation of this breaking change is very bad.

A developer shouldn't have to "patch" his dependencies to work.

arolariu avatar Jan 22 '26 20:01 arolariu

So we are doing the following

COPY app/.next/standalone/app ./
COPY app/.next/standalone/node_modules ./node_modules
COPY app/.next/static ./.next/static
COPY app/public ./public

as you may notice we didnt copy the app/.next/node_modules.

But app/.next/standalone/app/.next/node_modules should be copied over that way.

Could you share a small reproduction with a Dockerfile so I reproduce that?

mischnic avatar Jan 22 '26 22:01 mischnic

This seems like an awful developer experience...

I second that.

Here comes a minimal reproducible example @mischnic.

https://github.com/flodev/next-dependency-bug

its basically a turbo mono repo with a dockerfile that includes pino.

flodev avatar Jan 23 '26 08:01 flodev

This is my workaround script which works with namespaced packages:

RUN if [ -d ".next/node_modules" ]; then \
        cd .next/node_modules && \
        for link in ./*; do \
            if [ -L "$link" ]; then \
                target=$(readlink "$link"); \
                new_target=$(echo "$target" | sed 's#^../../../../../#../../#'); \
                echo "Creating symlink: $link -> $new_target"; \
                rm "$link"; \
                ln -s "$new_target" "$link"; \
            fi; \
        done; \
        for link in ./**/*; do \
            if [ -L "$link" ]; then \
                target=$(readlink "$link"); \
                new_target=$(echo "$target" | sed 's#^../../../../../#../../#'); \
                echo "Creating symlink: $link -> $new_target"; \
                rm "$link"; \
                ln -s "$new_target" "$link"; \
            fi; \
        done; \
    fi

avens19 avatar Jan 28 '26 20:01 avens19

Bun + TurboPack with a basic app is broken: https://gist.github.com/paralin/b6122f55896eb40b88aeebb211c7e496

paralin avatar Feb 20 '26 02:02 paralin

Any fix for this?

Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote 👍 on the issue description or subscribe to the issue for updates. Thanks!

Koyamie avatar Apr 09 '26 13:04 Koyamie