sidorares/node-mysql2 · error · TypeError

Bind parameters must not contain undefined

Error message

Bind parameters must not contain undefined

What it means

toParameter in lib/packets/encode_parameter.js:14-24 encodes a single prepared-statement bind value; the typeof switch throws TypeError for 'undefined' because, unlike null (which maps to Types.NULL at line 67-70), undefined has no valid MySQL wire representation. This is the prepared-statement execution-time counterpart to the execute() pre-check in connection.js:797.

Solutions

  1. Coalesce undefined to null before binding: values.map(v => v === undefined ? null : v).
  2. Avoid sparse arrays as bind parameters.
  3. Run the same Array.isArray + typeof validation that Connection.execute does, in any custom execute wrapper.

Example fix

// before
stmt.execute([maybeUndefined]);

// after
stmt.execute([maybeUndefined === undefined ? null : maybeUndefined]);
Defensive patterns

Strategy: validation

Validate before calling

const safeParams = (vals) => vals.map(v => v === undefined ? null : v);
// stmt.execute(safeParams(values));

Type guard

const hasNoUndefined = (vals) => vals.every(v => v !== undefined);

Prevention

When it happens

Trigger: A prepared-statement execute path that bypasses the connection.execute pre-check (e.g. a reused PreparedStatement with values containing undefined; an internal call to toParameter without prior validation); a value object that loses a key during serialization.

Common situations: Using the lower-level prepared-statement API directly; a custom execute wrapper that skips validation; sparse arrays as bind params ([1, , 3] where index 1 is a hole yielding undefined).

Related errors


AI-assisted analysis of sidorares/node-mysql2@8b1f829d37 (2026-08-11). Data as JSON: /api/errors/b6b04a9826b31313. Report an issue: GitHub.

Appendix: source

Thrown at lib/packets/encode_parameter.js:23

function isJSON(value) {
  return (
    Array.isArray(value) ||
    value.constructor === Object ||
    (typeof value.toJSON === 'function' && !Buffer.isBuffer(value))
  );
}

function toParameter(value, encoding, timezone, jsonAsString) {
  let type = Types.VAR_STRING;
  let length;
  let writer = function (value) {
    return Packet.prototype.writeLengthCodedString.call(this, value, encoding);
  };
  if (value !== null) {
    switch (typeof value) {
      case 'undefined':
        throw new TypeError('Bind parameters must not contain undefined');

      case 'number':
        type = Types.DOUBLE;
        length = 8;
        writer = Packet.prototype.writeDouble;
        break;

      case 'boolean':
        value = value | 0;
        type = Types.TINY;
        length = 1;
        writer = Packet.prototype.writeInt8;
        break;

      case 'object':
        if (Object.prototype.toString.call(value) === '[object Date]') {
          type = Types.DATETIME;
          length = 12;

View on GitHub (pinned to 8b1f829d37)