Next.js
Fixing Module not found: Can't resolve 'react': Root Cause and Resolution
This exception occurs when the Next.js build process or runtime cannot locate the `react` package within the `node_modules` directory or the configured module resolution paths. It is typically...
Fixing Module not found: Can't resolve 'react': Root Cause and Resolution
Problem Overview
This exception occurs when the Next.js build process or runtime cannot locate the react package within the node_modules directory or the configured module resolution paths. It is typically triggered by a missing dependency installation, a corrupted node_modules state, or a mismatch between the react and react-dom versions.
Root Cause
- Trigger: The
reactpackage is absent from the project'snode_modulesdirectory, or thepackage.jsondoes not listreactas a direct dependency. - Runtime Behavior: The Webpack or Turbopack bundler attempts to resolve the import statement
import React from 'react'(or implicit imports within Next.js internal components). When the module resolver fails to find the package entry point, it throws aModuleNotFoundErrorwith codeMODULE_NOT_FOUND.
Step-by-Step Fix
Step 1: Diagnose the State
Run the following command in your terminal to inspect the environment:
ls node_modules/react/package.json cat package.json | grep -E '"react"|"react-dom"'
Step 2: Apply the Fix
Provide the exact code patch, configuration change, or dependency update:
npm install react react-dom
Step 3: Verify the Resolution
Confirm the fix worked by running:
npm run build
Prevention
- Ensure
reactandreact-domare listed in thedependenciessection ofpackage.json. - Maintain version parity between
reactandreact-domto prevent peer dependency conflicts. - Avoid manually deleting
node_moduleswithout re-running the package manager's install command. - Use a lockfile (
package-lock.jsonoryarn.lock) to ensure consistent dependency resolution across environments.