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 react package is absent from the project's node_modules directory, or the package.json does not list react as 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 a ModuleNotFoundError with code MODULE_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 react and react-dom are listed in the dependencies section of package.json.
  • Maintain version parity between react and react-dom to prevent peer dependency conflicts.
  • Avoid manually deleting node_modules without re-running the package manager's install command.
  • Use a lockfile (package-lock.json or yarn.lock) to ensure consistent dependency resolution across environments.