ERR_REQUIRE_ESM
Attempted to require() an ES Module.
Usually happens because:
- ☑ Requiring ESM Package
- ☑ Self require()
🔍 Quick Checklist:
What is ERR_REQUIRE_ESM?
The ERR_REQUIRE_ESM error is thrown when a CommonJS script calls require() to load a module that has been compiled exclusively as an ES Module (ESM). Since ES Modules are loaded asynchronously, CommonJS synchronous require() functions cannot process them natively.
Common Causes
- Requiring ESM Package: A target npm dependency (like node-fetch v3 or chalk v5) is strictly ESM-only.
- Self require(): Running require() on a local file that has package.json type config set to 'module'.
| Cause | Frequency |
|---|---|
| Requiring ESM Package | ⭐⭐⭐⭐⭐ |
| Self require() | ⭐⭐⭐⭐ |
Common Mistakes
- Assuming all npm packages support CommonJS require() statements in older Node.js versions.
- Attempting to write top-level await in CommonJS scripts.
How to Fix
Framework-Specific Examples
Loading ESM dependencies dynamically inside an Express route handler.
app.post('/fetch-data', async (req, res, next) => {
try {
const { default: fetch } = await import('node-fetch');
const response = await fetch('https://api.com');
res.json(await response.json());
} catch (err) {
next(err);
}
});Server Configuration Examples
Tuning next.config.js to transpile strict ESM modules.
// next.config.js
module.exports = {
transpilePackages: ['node-fetch'],
};Best Practices
- Standardize on ESM ('type': 'module' inside package.json) for all new Node.js projects.
- Check package packaging details before updating dependencies.
Frequently Asked Questions (FAQ)
Q: Why does Node.js not allow require() on ES Modules?
Because ES Modules are loaded asynchronously during compile phases, whereas CommonJS `require()` is strictly synchronous. Sync operations cannot block thread execution to wait for async imports.
Q: How do I load an ESM package inside a CommonJS file?
Use dynamic imports: `import('package-name')`. Since it returns a promise, you can resolve it using `await` inside async functions.
Q: What is a 'Dual Module' package?
A dual module package provides both CommonJS (`exports.require`) and ES Module (`exports.import`) builds in its package.json configuration, allowing both require and import to work.
Q: How do I check if an npm package is ESM-only?
Inspect the package's `package.json`. If it contains 'type': 'module' and lacks a CommonJS entry file, it is ESM-only.