How to Fix: Error [ERR_REQUIRE_ESM]: require() of ES Module not supported.
Mixing CommonJS (require) with ES Modules (import).
What Causes It?
You are trying to use the old CommonJS syntax `require()` to import a modern package that is built as an ECMAScript Module (ESM). Node.js explicitly blocks importing ESM packages via `require()` because ESM loads asynchronously, while CommonJS loads synchronously.
Plain English Explanation
"Imagine trying to plug a modern USB-C cable into an old USB-A port. They just don't fit. You are using an old way to load code (`require`) on a package that demands the new way (`import`)."
Code Examples
// package.json does NOT have "type": "module"
// You are trying to import 'node-fetch' (an ESM only package)
const fetch = require('node-fetch'); // Throws ERR_REQUIRE_ESM// package.json MUST include: { "type": "module" }
// Use the modern import syntax
import fetch from 'node-fetch';
const response = await fetch('https://api.example.com');Step-by-Step Fix
- 1
Option 1 (Recommended): Convert your entire project to ES Modules. Open your `package.json` and add `"type": "module"` at the top level.
- 2
Once you add `type: module`, change all of your `require()` statements to `import` statements.
- 3
Option 2: If you must use CommonJS, either downgrade the package to an older version that still supports CommonJS, or use dynamic imports: `const module = await import('package-name')`.
Prevention Tips
- Always default to ES Modules (`import/export`) for any new Node.js project.
- Check the NPM documentation for the package you are installing to see if it is 'ESM Only'.
FAQs & Interview Prep
Why Interviewers Ask About This
High. Interviewers frequently ask about the differences between CommonJS and ES Modules, specifically regarding synchronous vs asynchronous loading.
Can I use 'import' without changing my package.json?
Yes, you can rename your specific file from `.js` to `.mjs`. Node.js will treat `.mjs` files as ES Modules automatically.