JavaScript Module Security (ESM vs CommonJS)
You'll learn: How the different JavaScript module systems create distinct security boundaries and risks in modern web applications.
Two Module Systems, Different Security Models
JavaScript has two primary module systems: CommonJS (Node.js's original system using require()) and ECMAScript Modules (ESM) (the standardized import/export syntax). Each has different security implications.
CommonJS loads modules synchronously and dynamically evaluates code at runtime. When you call require('./module'), the system executes that file immediately. This creates risks:
- Dynamic paths like
require(userInput)can load arbitrary code - No static analysis possible before execution
- Module content can be modified after loading
ESM was designed with security in mind. Imports are static declarations parsed before execution:
importstatements must use string literals (no dynamic paths in the declaration itself)- Modules are parsed and validated before any code runs
- Stricter scoping and immutable bindings prevent tampering
Dynamic Imports and Security
ESM supports dynamic imports via import() function, which reintroduces some flexibility but requires careful validation:
// Risky - user-controlled path
const module = await import(userProvidedPath); // Potential code injection
// Safer - whitelist approach
const allowedModules = ['./safe1.js', './safe2.js'];
if (allowedModules.includes(userChoice)) {
const module = await import(userChoice);
}
Import Maps and Module Integrity
Import maps let you control module resolution, but misconfiguration can redirect imports to malicious sources. Always verify module integrity using Subresource Integrity (SRI) for external modules when possible.
Key Takeaway: ESM provides better security through static analysis and stricter semantics than CommonJS, but dynamic imports and import maps require careful validation to prevent loading untrusted code into your application's execution context.