Class cannot be constructed directly
Quick Answer
Use the public constructor or factory function documented in the Node.js API — do not attempt to construct internal subclasses directly.
Production Risk
Programming error — indicates incorrect API usage.
Thrown when attempting to directly instantiate an internal class that disallows direct construction. Commonly seen with Web Streams API classes (ReadableStream, WritableStream, TransformStream) when used in contexts that try to subclass or construct internal variants.
- 1Calling new on an internal class that requires a specific factory pattern
- 2Subclassing a Web Streams API class incorrectly without calling super() with required internal slot arguments
- 3Using reflect/proxy tricks to bypass constructor guards on Node.js internals
Fix
Use the public API constructor
WHEN When you need a ReadableStream or similar class
const { ReadableStream } = require('stream/web');
// Correct: use the public constructor with an underlying source
const stream = new ReadableStream({
start(controller) {
controller.enqueue('hello');
controller.close();
}
});Why this works
The public ReadableStream constructor accepts an underlying source object — this is the only supported construction path.
try {
new InternalClass();
} catch (err) {
if (err.code === 'ERR_ILLEGAL_CONSTRUCTOR') {
console.error('Use the public factory instead');
}
}✕ Use Object.create() or Reflect.construct() to bypass the illegal constructor check
Internal classes depend on private slots set in the constructor; bypassing it produces an unusable object that will throw on any method call.
ERR_ILLEGAL_CONSTRUCTOR became more common with the Web Streams API (ReadableStream, WritableStream) added in Node.js 18.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev