ERR_BUFFER_OUT_OF_BOUNDS
Node.jsERRORNotableBufferHIGH confidence

A buffer operation is out of bounds.

Production Risk

High. This is a serious memory management error that can lead to application crashes and, in worst-case scenarios, security vulnerabilities.

What this means

This error occurs when you attempt to read or write data outside the allocated boundaries of a Buffer instance. Buffers are fixed-size memory allocations, and any access before the start (index < 0) or after the end (index >= buffer.length) is an invalid operation that triggers this protective error.

Why it happens
  1. 1Providing an `offset` to a buffer method (e.g., `buf.readInt8(offset)`) that is negative or larger than the buffer's capacity.
  2. 2A calculation for an offset or length results in an incorrect value.
  3. 3Attempting to write data that is larger than the remaining space in the buffer from the given offset.
How to reproduce

This error is thrown by methods on the `Buffer` prototype when an operation's target offset and length would cause a memory access outside the buffer's defined range.

trigger — this will error
trigger — this will error
const buf = Buffer.alloc(4);

try {
  // Attempt to write an integer at an offset that doesn't exist.
  buf.writeInt8(10, 5);
} catch (err) {
  console.error(err.code);
}

expected output

ERR_BUFFER_OUT_OF_BOUNDS

Fix

Validate Offset and Length

WHEN Performing read or write operations on a buffer.

Validate Offset and Length
const buf = Buffer.alloc(8);
const offset = 10;
const value = 123;

// Check if the write operation will fit.
if (offset + 1 <= buf.length) { // +1 for byte length of Int8
  buf.writeInt8(value, offset);
} else {
  console.error('Write operation is out of bounds.');
}

Why this works

Before calling a buffer method, always validate that your offset and length parameters are within the valid range of the buffer's size (`0` to `buf.length - 1`).

Code examples
Triggerjs
const buf = Buffer.alloc(4);

try {
  // Attempt to write an integer at an offset that doesn't exist.
  buf.writeInt8(10, 5);
} catch (err) {  // this triggers ERR_BUFFER_OUT_OF_BOUNDS
Handle in try/catchjs
try {
  // operation that may throw ERR_BUFFER_OUT_OF_BOUNDS
  riskyOperation()
} catch (err) {
  if (err.code === 'ERR_BUFFER_OUT_OF_BOUNDS') {
    console.error('ERR_BUFFER_OUT_OF_BOUNDS:', err.message)
  } else {
    throw err
  }
}
Defensive pattern to avoid itjs
const buf = Buffer.alloc(8)
const offset = 2
if (offset + 1 <= buf.length) {
  buf.writeInt8(42, offset)  // safe
}
What not to do

Sources
Official documentation ↗

https://github.com/nodejs/node/blob/main/lib/buffer.js

More information

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Node.js errors