How to Fix Node.js Module Not Found in ESM
In this tutorial, you'll learn about How to Fix Node.js Module Not Found in ESM. We cover key concepts, practical examples, and best practices.
The Problem
You use import syntax in Node.js and get:
node:internal/process/esm_loader:40
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/app/utils' imported from /app/server.js
Did you mean to import "./utils.js"?
Or:
SyntaxError: Cannot use import statement outside a module
Node.js ESM (ECMAScript Modules) requires file extensions in import paths and a "type": "module" in package.json.
Quick Fix
Step 1: Add file extensions
CommonJS allows require("./utils") without extension, but ESM requires the full path:
// Wrong
import { helper } from "./utils";
// Right
import { helper } from "./utils.js";
Step 2: Set type to module in package.json
npm pkg set type=module
Or add to package.json manually:
{
"type": "module"
}
Step 3: Use .mjs extension
Alternatively, rename files to .mjs:
mv server.js server.mjs
node server.mjs
The .mjs extension forces ESM mode regardless of package.json.
Step 4: Fix package imports
For npm packages, ensure the package name is correct:
// Wrong -- typo
import express from "expresss";
// Right
import express from "express";
Check if the package is installed:
npm ls express
Alternative Solutions
Keep using CommonJS with .cjs extension or set "type": "commonjs":
mv server.js server.cjs
node server.cjs
Or use dynamic imports in CommonJS:
const { helper } = await import("./utils.js");
Check Node.js and npm Versions
node --version
# v18.17.0
npm --version
# 9.6.7
Verify your runtime versions before troubleshooting module resolution or compatibility issues. Outdated versions of Node.js or npm are a common source of mysterious errors. Use nvm to manage multiple Node versions side by side.
Additional Troubleshooting
# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"
If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.
Prevention
- Decide on ESM vs CommonJS at project start and set
typeinpackage.json. - Always include file extensions in import paths.
- Use
*.mjsfor ESM files in mixed-type projects. - Use
*.cjsfor CommonJS files in ESM projects.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro