Node.js: ReferenceError: require is not defined in ES module scope
ReferenceError: require is not defined in ES module scope, you can use import instead
at file:///app/server.js:4:14
Immediate Remediation
typescript
// Option 1: Use modern ESM import:
import path from 'node:path';
// Option 2: If dynamic CommonJS require is required in an ES Module:
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const pkg = require('./package.json');Root Cause Analysis
The project package.json has "type": "module" enabled, which removes CommonJS globals (require, __dirname, __filename) from top-level execution scope.
Verification & Guardrails
- To get __dirname in ESM: import { fileURLToPath } from "node:url"; const __dirname = path.dirname(fileURLToPath(import.meta.url));
- Rename file to .cjs if you want it to execute as legacy CommonJS without refactoring.
Have a custom or uncategorized crash?
Run your trace through our in-memory client privacy sandbox for instant SRE remediation.