Buffer size exceeds the maximum allowed limit
Production Risk
High — unbounded buffer allocation from external input is a DoS vector.
Thrown when an attempt is made to create a Buffer larger than the maximum allowed size (currently 2 GB - 1 byte on 64-bit platforms, limited by V8s typed array size limit). Allocating a buffer this large would exhaust process memory.
- 1Allocating Buffer.alloc() or Buffer.allocUnsafe() with a size > 2^31 - 1
- 2Computing a buffer size from untrusted input that overflows
- 3Concatenating many buffers into a single allocation without a size check
Triggered when Buffer.alloc() or related methods receive a size argument exceeding the platform maximum.
const size = 2 ** 31; // 2 GB — exceeds the limit const buf = Buffer.alloc(size); // throws ERR_BUFFER_TOO_LARGE
expected output
RangeError [ERR_BUFFER_TOO_LARGE]: Cannot create a Buffer larger than 2147483647 bytes
Fix 1
Validate buffer sizes before allocation
WHEN When buffer size comes from external input or computation
const MAX = 1024 * 1024 * 512; // 512 MB application limit
if (size > MAX) throw new Error(`Requested size ${size} exceeds limit`);
const buf = Buffer.alloc(size);Why this works
Capping size before allocation prevents both the Node.js error and accidental OOM.
Fix 2
Stream large data instead of buffering it all at once
WHEN When handling large files or network payloads
const { createReadStream } = require('fs');
const src = createReadStream('/path/to/large-file');
src.pipe(destination); // process chunk by chunkWhy this works
Streaming avoids the need for a single large buffer allocation entirely.
const size = 2 ** 31; // 2 GB — exceeds the limit const buf = Buffer.alloc(size); // throws ERR_BUFFER_TOO_LARGE // this triggers ERR_BUFFER_TOO_LARGE
try {
// operation that may throw ERR_BUFFER_TOO_LARGE
riskyOperation()
} catch (err) {
if (err.code === 'ERR_BUFFER_TOO_LARGE') {
console.error('ERR_BUFFER_TOO_LARGE:', err.message)
} else {
throw err
}
}const MAX = 512 * 1024 * 1024 // 512 MB
if (size > MAX) throw new RangeError(`Size ${size} exceeds limit`)
const buf = Buffer.alloc(size)✕ Trust user-supplied sizes for buffer allocation
Malicious or erroneous sizes can cause DoS via allocation errors or OOM.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev