Skip to content
Latchkey

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.

next build
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

  1. Add the missing package to dependencies.
  2. Run npm install to update the lockfile, then commit it.
  3. Re-run npm ci and next build to confirm.
Terminal
npm install clsx
git add package.json package-lock.json

Keep 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.

Terminal
npm ci

How to prevent it

  • Declare every imported package in dependencies.
  • Commit package-lock.json with each dependency change.
  • Use npm ci in CI to catch drift early.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →