sidorares/node-mysql2 · error · Error

"database" connection config property must be a string

Error message

"database" connection config property must be a string

What it means

When serialising a COM_CHANGE_USER packet, mysql2 requires the `database` property to be a string. A missing or non-string `database` (null, number, undefined) makes the packet unbuildable, so the call throws immediately. Note the property must be present as a string even if it is empty.

Source

Thrown at lib/packets/change_user.js:89

      }
      packet.writeLengthCodedNumber(keysLength);
      for (let k = 0; k < attrNames.length; ++k) {
        packet.writeLengthCodedString(attrNames[k], encoding);
        packet.writeLengthCodedString(
          connectAttributes[attrNames[k]],
          encoding
        );
      }
    }
    return packet;
  }

  toPacket() {
    if (typeof this.user !== 'string') {
      throw new Error('"user" connection config property must be a string');
    }
    if (typeof this.database !== 'string') {
      throw new Error('"database" connection config property must be a string');
    }
    // dry run: calculate resulting packet length
    const p = this.serializeToBuffer(Packet.MockBuffer());
    return this.serializeToBuffer(Buffer.allocUnsafe(p.offset));
  }
}

module.exports = ChangeUser;

View on GitHub (pinned to 5ebe8903d6)

Solutions

  1. Always include `database` as a string, using `''` if you want no default database: `changeUser({ user: 'bob', database: '' })`.
  2. Coerce the value: `changeUser({ user, database: String(dbName ?? '') })`.

Example fix

// before
connection.changeUser({ user: 'bob' });

// after
connection.changeUser({ user: 'bob', database: '' });
Defensive patterns

Strategy: validation

Validate before calling

function changeUserSafe(conn, opts) {
  const database = opts.database == null ? '' : String(opts.database);
  return conn.changeUser({ ...opts, database: String(database) });
}

Type guard

function isValidDatabase(db) {
  return typeof db === 'string';
}

Prevention

When it happens

Trigger: Calling `connection.changeUser({ user: 'bob' })` without a `database` field; or `changeUser({ user, database: null })`. The constructor defaults `database` to `''`, but an explicit non-string overrides that and fails the check.

Common situations: Switching user but intending to keep/empty the current database and forgetting to pass `database: ''`; passing a numeric or object database value from unvalidated input.

Related errors


AI-assisted analysis of sidorares/node-mysql2@5ebe8903d6 (2026-08-03). Data as JSON: /data/errors/68f7cd0c50a01d84.json. Report an issue: GitHub.