Node.js ERR_MODULE_NOT_FOUND — Fix Module Resolution Errors

Fix ERR_MODULE_NOT_FOUND and MODULE_NOT_FOUND errors in Node.js. Covers ESM vs CJS resolution, package.json exports field, and common import path issues.

Node.js Error Codes

Detailed Explanation

Node.js Module Resolution Errors

Module not found errors are the most common startup failures in Node.js applications. There are two variants:

  • MODULE_NOT_FOUND — Classic require() (CommonJS) failure
  • ERR_MODULE_NOT_FOUND — Modern import (ESM) failure

Most Common Causes

1. Package not installed:

# Fix: install the missing package
npm install missing-package

# Verify it exists in node_modules
ls node_modules/missing-package

2. Incorrect relative path:

// Wrong: missing file extension in ESM
import { helper } from './utils';

// Right: ESM requires explicit extensions
import { helper } from './utils.js';

3. Package.json "exports" field blocking access:

{
  "exports": {
    ".": "./dist/index.js",
    "./utils": "./dist/utils.js"
  }
}

With an exports map, deep imports like package/src/internal are blocked unless explicitly listed.

4. ESM/CJS mismatch (ERR_REQUIRE_ESM):

// Package is ESM-only (type: "module" in their package.json)
// Solution 1: Use dynamic import
const pkg = await import('esm-only-package');

// Solution 2: Pin to last CJS version
// npm install esm-only-package@2  (if v2 was last CJS)

Node.js Module Resolution Algorithm

CommonJS (require):

  1. Check core modules (fs, path, etc.)
  2. Check node_modules in current directory
  3. Walk up parent directories checking node_modules
  4. Check global modules

ESM (import):

  1. Check package.json "exports" map
  2. Check package.json "main" field
  3. Look for index.js in directory
  4. File extensions are mandatory for relative imports

Debugging Steps

# Check where Node looks for modules
node -e "console.log(require.resolve.paths('pkg'))"

# Check the resolved path
node -e "console.log(require.resolve('pkg'))"

# Clear module cache
rm -rf node_modules && npm install

Use Case

Module resolution errors account for a significant portion of Node.js startup failures, especially in projects transitioning from CommonJS to ES Modules, monorepos with workspace dependencies, or when upgrading packages that switched to ESM-only distribution. Understanding the resolution algorithm prevents wasted debugging time.

Try It — Error Code Reference

Open full tool