Why are cached node_modules binaries failing with "Cannot find module" errors?
Last updated: June 29, 2026
Context
When using cached node_modules in CI workflows, you may encounter errors where binary executables fail with "Cannot find module" errors, even though the packages appear to be properly cached. This typically manifests as errors like:
Error: Cannot find module './dist/index.js'
Require stack:
- /home/builder/clone/node_modules/.bin/patch-packageThe issue occurs because the .bin directory contains environment-specific shims that aren't meant to be persisted across builds. When restored from cache, these shims can point to incorrect paths.
Answer
To resolve this issue while maintaining the performance benefits of caching node_modules, add a step to delete the .bin directory before running npm install:
Add the following commands to your workflow before npm install:
rm -rf $CM_BUILD_DIR/node_modules/.bin npm install
This approach allows npm to regenerate the binary shims fresh on each run while still benefiting from cached packages, avoiding the significant performance hit of switching to ~/.npm caching.
Alternative solution: If you prefer to avoid this workaround, you can cache ~/.npm instead of node_modules. However, this will result in longer build times as npm will need to reinstall packages even though it skips re-downloading them.
The recommended solution maintains nearly the same performance as full node_modules caching while ensuring binary executables work correctly across different build environments.