Node.js Modules: CommonJS vs ES Modules Explained (2026-27)
If you've followed our earlier guides on getting started and essential commands, you already know how to run a single JavaScript file with Node.js. Real applications, however, are almost never one file - they're split across many files that need to share code with each other. That sharing is handled by a module system, and Node.js actually supports two of them side by side: the original CommonJS system built around
require(), and the newer ES Modules system built around import and export, which matches the module syntax used natively in web browsers. This tutorial walks through both systems in detail, compares them directly, explains how to mix them safely, and helps you decide which one to reach for in your own projects.
📋 Table of Contents
- What Is a Module in Node.js?
- Why Modules Matter
- CommonJS Modules Explained
- require() And module.exports In Detail
- ES Modules Explained
- import And export In Detail
- Enabling ES Modules In Node.js
- CommonJS vs ES Modules: Key Differences
- File Extensions: .js, .cjs And .mjs
- Default Exports vs Named Exports
- Dynamic Imports
- Interoperability Between CommonJS And ESM
- __dirname, __filename And import.meta.url
- Top-Level Await
- Circular Dependencies In Both Systems
- Which Module System Should You Use?
- Common Mistakes With Node.js Modules
- Migration Tips: CommonJS To ES Modules
- Quick Reference Table
- Try It Yourself: Code Playground
- Practice Quiz
- Frequently Asked Questions (FAQ)
✅ What Is a Module in Node.js?
A module is simply a single file of JavaScript code that Node.js treats as its own self-contained unit. Anything you declare inside a module - a variable, a function, a class - stays private to that file by default. Nothing "leaks" into other files automatically, which is very different from how a browser behaves when you load several plain <script> tags on one page, where every variable ends up sharing the same global space.
Instead, a module has to deliberately choose what it wants to share with the rest of the application. It does this by exporting specific pieces of code. Any other file that wants to use that shared code has to explicitly import it. This "export what you want, import what you need" pattern is the foundation of how every non-trivial Node.js application is organized - from a two-file hobby project to a codebase with thousands of files.
Node.js has supported this idea since its very first versions, through a system now known as CommonJS. Years later, as JavaScript itself gained an official, standardized module syntax as part of the ECMAScript specification, Node.js added support for that too, known as ES Modules (often abbreviated ESM). Both systems are still fully supported today, and understanding both - along with how they interact - is essential for working comfortably in the current Node.js ecosystem.
✅ Why Modules Matter
It's worth pausing on why module systems exist at all before comparing the two. Splitting code into modules brings several concrete, practical benefits to any project larger than a single script:
- Organization - related code (like all database logic, or all routing logic) can live together in its own file rather than one enormous file.
- Reusability - a helper function written once can be imported and reused across many parts of an application, or even published as an npm package for other projects entirely.
- Encapsulation - internal implementation details stay hidden inside a module unless they are deliberately exported, reducing accidental interference between unrelated parts of a codebase.
- Maintainability - smaller, focused files are easier to read, test, debug, and hand off to another developer than one sprawling file with everything mixed together.
- Dependency management - modules make it explicit exactly which files depend on which other files, which tooling can then analyze, bundle, or optimize.
Every npm package you've ever installed - Express, Axios, Lodash, and thousands of others - is itself just a module, or a collection of modules, packaged up for others to import into their own projects. Understanding modules deeply is really understanding how the entire Node.js and npm ecosystem fits together.
✅ CommonJS Modules Explained
CommonJS is the module system Node.js has used since its earliest releases, long before JavaScript itself had any official module syntax of its own. It was designed specifically for server-side JavaScript, where files are typically loaded from a local disk, making synchronous loading fast and simple to implement.
Under CommonJS, every file is automatically wrapped by Node.js in a function behind the scenes, which is what gives each file access to a handful of special variables without you ever needing to declare them - things like require, module, exports, __dirname, and __filename. You don't see this wrapping directly, but it explains why these variables "just work" inside any CommonJS file without an explicit import.
// math-utils.js - a small CommonJS module
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = { add, subtract };
// app.js - importing the CommonJS module above
const { add, subtract } = require('./math-utils');
console.log(add(4, 3)); // 7
console.log(subtract(10, 6)); // 4
Notice the file path doesn't need a .js extension when requiring a local file - Node.js resolves that automatically. CommonJS has been the default module system for essentially all of Node.js's history, which is why the overwhelming majority of existing npm packages, tutorials, and production codebases still use it today.
✅ require() And module.exports In Detail
Two pieces make CommonJS work: require() for pulling code in, and module.exports (or the shorthand exports) for pushing code out. It's worth understanding each a little more closely.
require()
require() is a function that takes a module identifier - a relative path, an absolute path, or simply a package name - and returns whatever that module exported. Node.js caches the result the first time a module is required, so requiring the same file again later in the same process returns the same cached object rather than re-running the file's code.
// Three common ways to use require()
const fs = require('fs'); // a built-in Node.js module
const express = require('express'); // a package from node_modules
const config = require('./config'); // a local file, relative to this one
module.exports and exports
Every CommonJS file has a module object automatically available, and module.exports is what actually gets returned to whoever calls require() on that file. By default, module.exports starts as an empty object, and exports is simply a shortcut reference pointing to that same object - which is why you'll often see both used, though they behave slightly differently once reassigned.
// Attaching properties works with either exports or module.exports
exports.greet = function(name) {
return `Hello, ${name}!`;
};
// But REPLACING the export entirely must use module.exports
module.exports = function(name) {
return `Hello, ${name}!`;
};
exports directly, like exports = { greet }, silently breaks the connection to module.exports and nothing gets exported at all. Always use module.exports when replacing the whole export value, and reserve plain exports.property for adding individual named exports.
✅ ES Modules Explained
ES Modules, often shortened to ESM, are the official module system defined as part of the JavaScript language specification itself - not something Node.js invented on its own. Because ES Modules are a language-level feature, the same import and export syntax works in modern web browsers as well as in Node.js, which is one of the biggest reasons developers have gradually been adopting it.
Unlike CommonJS, ES Modules are statically analyzed - meaning the imports and exports of a file can be determined just by reading its structure, before any code actually runs. This static structure is what allows tools like bundlers to perform optimizations such as "tree-shaking," where unused exports are automatically stripped out of a final bundle.
// math-utils.mjs - a small ES Module
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// app.mjs - importing the ES Module above
import { add, subtract } from './math-utils.mjs';
console.log(add(4, 3)); // 7
console.log(subtract(10, 6)); // 4
Notice two structural differences right away: ES Module imports must include the file extension, and import/export statements can normally only appear at the top level of a file, not inside conditional blocks or functions - a direct consequence of ESM's static, analyze-before-running design.
✅ import And export In Detail
ES Modules offer more than one way to export values, which gives you flexibility depending on how a module is meant to be used elsewhere.
Named Exports
// Exporting multiple named values from one file
export const PI = 3.14159;
export function circleArea(radius) {
return PI * radius * radius;
}
// Importing specific named values, exactly by name
import { PI, circleArea } from './geometry.mjs';
Default Exports
// Exporting one primary value as the default
export default function logger(message) {
console.log(`[LOG]: ${message}`);
}
// Importing a default export - the name here is your choice
import logger from './logger.mjs';
Importing Everything As a Namespace
// Grabbing every named export as properties of one object
import * as geometry from './geometry.mjs';
console.log(geometry.circleArea(5));
✅ Enabling ES Modules In Node.js
By default, Node.js treats plain .js files as CommonJS. To use ES Module syntax, you need to tell Node.js explicitly, and there are two straightforward ways to do it.
| Method | How It Works |
|---|---|
| package.json field | Add "type": "module" to package.json, and every .js file in that project is treated as an ES Module. |
| .mjs extension | Name a file with a .mjs extension, and Node.js treats it as an ES Module regardless of the type field. |
{
"name": "my-esm-project",
"version": "1.0.0",
"type": "module"
}
"type": "module" once in package.json is more convenient than renaming every file to .mjs individually - you only need the .mjs extension for the rare file you want treated as an ES Module in an otherwise CommonJS project.
✅ CommonJS vs ES Modules: Key Differences
With both systems explained individually, here is a direct, side-by-side comparison of how they differ in practice.
| Aspect | CommonJS | ES Modules |
|---|---|---|
| Import syntax | require('./file') | import x from './file.js' |
| Export syntax | module.exports = value | export / export default |
| Loading style | Synchronous | Asynchronous, non-blocking |
| File extension in imports | Optional | Required |
| Analysis timing | Resolved at runtime | Statically analyzed before execution |
| Placement of import/export | Anywhere, including inside functions | Top level only (with dynamic import() as the exception) |
| Special variables | __dirname, __filename, require, module, exports | import.meta.url (no __dirname or require by default) |
| Top-level await | Not supported | Supported |
| Browser compatibility | Not natively supported by browsers | Natively supported by modern browsers |
| Default in Node.js | Yes, unless configured otherwise | Only when explicitly enabled |
Neither system is objectively "better" in every situation - CommonJS remains simpler for quick synchronous scripts and has decades of package support behind it, while ES Modules align with the broader JavaScript language standard and unlock features unavailable in CommonJS, such as top-level await.
✅ File Extensions: .js, .cjs And .mjs
Node.js uses three relevant extensions to decide how to interpret a file, and mixing them intentionally is a common, supported pattern.
This becomes especially useful when a mostly-CommonJS project needs just one file to use ES Module syntax, or the reverse - an ESM project needs one specific file to fall back to CommonJS, perhaps because it depends on a package that only works with require().
✅ Default Exports vs Named Exports
Choosing between a default export and named exports is a design decision worth thinking about deliberately, not just a syntax preference.
| Use a default export when... | Use named exports when... |
|---|---|
| The module has one clear, primary purpose (a single class or function). | The module offers several related utilities that make sense used independently. |
| You want the importing file to be free to name it anything it likes. | You want consistent, predictable names enforced across every file that imports them. |
| Example: a single Express router, a single database connection function. | Example: a math-utilities file exporting add, subtract, multiply separately. |
Many real-world files use both at once - a default export for the module's main purpose, alongside a few smaller named exports for supporting pieces. CommonJS achieves something similar by exporting an object with named properties, though it lacks a dedicated "default" concept of its own.
✅ Dynamic Imports
Static import statements must sit at the top level of a file, but sometimes you only want to load a module conditionally - for example, only when a certain feature is actually used. Both module systems offer a way to do this, though they look different.
// Dynamic import inside an ES Module - returns a Promise
if (needsPdfExport) {
const { generatePdf } = await import('./pdf-generator.mjs');
generatePdf(reportData);
}
Interestingly, this dynamic import() function is available inside CommonJS files too, since it always returns a Promise rather than relying on ESM's static analysis. This makes it one of the easiest ways for a CommonJS file to load an ES-Module-only package on demand.
✅ Interoperability Between CommonJS And ESM
Real projects often need both systems to coexist, especially while migrating gradually or when depending on packages written for the other system. Node.js provides specific rules for this.
Importing CommonJS from an ES Module
This direction generally works smoothly. A CommonJS module's module.exports object becomes available as the default export when imported from an ES Module.
// Importing a CommonJS package from within an ES Module file
import express from 'express'; // works, even though express is CommonJS
Importing an ES Module from CommonJS
This direction is more restricted - a CommonJS file cannot use require() directly on a pure ES Module, because require is synchronous while ESM loading is asynchronous. The workaround is a dynamic import instead.
// Loading an ES-Module-only package from a CommonJS file
async function loadIt() {
const mod = await import('some-esm-only-package');
mod.doSomething();
}
Using require() Inside an ES Module
ES Modules don't have require defined at all by default. When you specifically need it - for example, to load a CommonJS-only package that has no ESM build - Node.js's built-in module module provides a way to construct one.
// Recreating require() inside an ES Module, when truly needed
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const legacyPackage = require('some-commonjs-only-package');
✅ __dirname, __filename And import.meta.url
CommonJS automatically gives every file two handy globals: __dirname (the folder containing the current file) and __filename (the full path to the current file itself). Neither exists in ES Modules, since ESM was designed to also run in browsers, where a traditional filesystem path doesn't make sense.
// CommonJS - __dirname and __filename are simply available
console.log(__dirname);
console.log(__filename);
Inside an ES Module, the equivalent starting point is import.meta.url, a URL-formatted string identifying the current module, which is usually combined with Node's built-in url module to derive a usable path.
// ES Modules - deriving the equivalent of __dirname
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log(__dirname);
✅ Top-Level Await
One of the more practically useful features unique to ES Modules is top-level await - the ability to use the await keyword directly at a file's top level, outside of any async function.
// This works directly in an ES Module - no wrapping async function needed
const response = await fetch('https://api.example.com/config');
const config = await response.json();
console.log(config);
In CommonJS, the same result requires wrapping the code in an immediately-invoked async function, since await is only valid inside a function marked async:
// CommonJS equivalent - a wrapper is required
(async () => {
const response = await fetch('https://api.example.com/config');
const config = await response.json();
console.log(config);
})();
Top-level await is particularly convenient for configuration files, database connection setup, or any script that genuinely needs to finish an asynchronous step before the rest of the file makes sense to run.
✅ Circular Dependencies In Both Systems
A circular dependency happens when module A imports module B, and module B also imports module A, directly or through a longer chain. Both CommonJS and ES Modules can handle this without crashing, but the results can differ subtly.
In CommonJS, if module A is still in the middle of executing when module B requires it back, module B receives whatever partial module.exports object A has built up so far - which may be missing values defined later in A's file. In ES Modules, thanks to static analysis, bindings are "live" references rather than copied values, which can make circular references behave slightly more predictably, though it doesn't eliminate the underlying design problem.
✅ Which Module System Should You Use?
With both systems fully explained, the practical question remains: which should you actually choose for your own project?
🟦 Choose CommonJS if...
You're maintaining or extending an existing large CommonJS codebase, working with older packages that lack ESM support, or you simply want the most universally compatible default with the least friction against the wider existing npm ecosystem.
🟩 Choose ES Modules if...
You're starting a brand-new project, want your server-side code to share syntax with front-end JavaScript, plan to use top-level await, or want to align with where the JavaScript language itself, and most modern tooling, is heading.
There's no strict deadline forcing every project to switch - both systems are actively supported by Node.js, and many production applications happily run on CommonJS indefinitely. The important thing is understanding both well enough to read, debug, and interoperate with whichever one a given project, package, or tutorial happens to use.
✅ Common Mistakes With Node.js Modules
- Mixing require() and import in the same file without realizing the file's module type, causing a confusing SyntaxError.
- Forgetting the file extension in an ES Module import path - required in ESM, optional in CommonJS.
- Reassigning exports directly in CommonJS instead of module.exports, silently losing the intended export.
- Expecting __dirname to exist inside an ES Module without deriving it from import.meta.url first.
- Using require() on a pure ESM-only package from a CommonJS file, instead of switching to a dynamic import().
- Setting "type": "module" in package.json without updating every existing require() call, breaking the whole project at once.
✅ Migration Tips: CommonJS To ES Modules
If you decide to migrate an existing CommonJS project to ES Modules, a gradual, careful approach avoids breaking everything in a single step.
- Audit your dependencies first. Confirm the packages your project relies on either support ESM or still work fine when imported from an ESM file.
- Start with leaf files. Convert files with few or no internal dependencies first, since they're the lowest risk to update.
- Replace require() with import, and remember to add the file extension to every relative import path.
- Replace module.exports with export / export default, deciding deliberately between named and default exports as you go.
- Replace __dirname and __filename wherever they appear with the import.meta.url-based equivalent shown earlier in this guide.
- Set "type": "module" in package.json only once the majority of the codebase is ready, or convert incrementally using individual .mjs files first.
- Run your test suite after every batch of changes, rather than converting the entire project in one uninterrupted pass.
✅ Node.js Modules - Quick Reference Table
| Term | One-Line Meaning |
|---|---|
| Module | A single file whose code stays private unless explicitly exported. |
| CommonJS | Node.js's original module system, based on require() and module.exports. |
| ES Modules (ESM) | The official JavaScript-language module system, based on import and export. |
| Named export | An export identified by a specific, fixed name at import time. |
| Default export | A module's single primary export, freely renamed by whoever imports it. |
| Dynamic import() | A Promise-based way to load a module conditionally, anywhere in a file. |
| Top-level await | Using await directly at a file's top level, only available in ES Modules. |
| import.meta.url | An ES Module's equivalent starting point for deriving its own file path. |
✅ Try It Yourself: Code Playground
Edit the JavaScript below and click "Run" to see simulated console output. This mirrors patterns you would use in a real module - defining and calling small exported-style functions.
✅ Practice - Yes / No Quiz
1. Does CommonJS load modules synchronously by default?
2. Is a file extension required when importing a local file in an ES Module?
3. Does __dirname work automatically inside a native ES Module?
4. Does top-level await work in a native ES Module without wrapping it in an async function?
5. Does a .cjs file get treated as an ES Module even if package.json sets "type": "module"?