Next.js "Cannot find module" after npm ci in CI
A clean npm ci installs exactly what the lockfile records. If a module is imported but not in package.json (or the lockfile is out of date), the build fails with "Cannot find module" even though it worked from a stale local node_modules.
What this error means
next build throws "Error: Cannot find module 'X'" or "Cannot find module 'next/...'" immediately after a clean install, often only in CI where node_modules is built fresh.
Error: Cannot find module 'clsx'
Require stack:
- /home/runner/work/app/app/.next/server/app/page.js
at Module._resolveFilename (node:internal/modules/cjs/loader)Common causes
The dependency is used but not declared
The import worked locally from a transitive or leftover install, but it is not in package.json, so npm ci does not install it.
The lockfile is out of sync with package.json
A drifted lockfile makes npm ci install a set that does not include the needed module.
How to fix it
Declare the dependency and refresh the lockfile
- Add the missing package to dependencies.
- Run
npm installto update the lockfile, then commit it. - Re-run
npm ciand next build to confirm.
npm install clsx
git add package.json package-lock.jsonKeep package.json and lockfile in sync
Use npm ci in CI so the install fails loudly on drift instead of silently resolving from a stale tree.
npm ciHow to prevent it
- Declare every imported package in dependencies.
- Commit package-lock.json with each dependency change.
- Use
npm ciin CI to catch drift early.