How to fix "Module Not Found" error in Next.js?
Issue
When running npm run dev
or next build
, I get the following error:
ModuleNotFoundError: Module not found: Error: Can't resolve 'some-package' in '/path/to/project'
or
Error: Cannot find module 'some-package'
Require stack:
- /path/to/project/.next/server/pages/index.js
- /path/to/project/node_modules/next/dist/next-server/server/next-server.js
- /path/to/project/node_modules/next/dist/server/next.js
- /path/to/project/server.js
This happens even though I have installed the package and correctly imported the module.
Solution
It’s not really clear from your description, this could be caused by many factors. Here are a few solutions you can try:
1. Check the Module Path
Ensure the import statement is correct and matches the actual file name (case-sensitive in Linux/macOS).
import myComponent from './components/MyComponent'; // ✅ Correct
If the file is named mycomponent.js
, but you import MyComponent.js
, it will fail on Linux/macOS.
2. Reinstall Dependencies
Sometimes, corrupted node_modules
or package-lock.json
can cause this issue. Run:
rm -rf node_modules package-lock.json && npm install
Or for Yarn:
rm -rf node_modules yarn.lock && yarn install
3. Missing Dependency
If the error mentions a missing package, install it explicitly:
npm install some-package
4. Check for Typos in Import Statements
If you misspell the module name in your import, you will get this error. Double-check your imports.
5. Clear Next.js Cache
Sometimes, Next.js caches build artifacts that cause errors. Try:
next build --no-cache
6. Check tsconfig.json or jsconfig.json (if using TypeScript or absolute imports)
If you’re using absolute imports, ensure your tsconfig.json
or jsconfig.json
contains:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["components/*"]
}
}
}
Then restart the dev server.
7. Use require.resolve to Debug
Run this in your project root to check if the module is installed:
node -e "console.log(require.resolve('some-package'))"
If it fails, the package is not installed correctly.
If none of these solutions work, try deleting the .next/
directory and restarting the project.