sidorares/node-mysql2 · error · TypeError

Unknown charset

Error message

Unknown charset '${charset}'

What it means

ConnectionConfig.getCharsetNumber (lib/connection_config.js:256-262) uppercases the charset string and looks it up in the Charsets constant map; if not found it throws TypeError. The lookup must match MySQL's charset name (e.g. UTF8MB4_UNICODE_CI) exactly after uppercasing.

Solutions

  1. Use the exact MySQL charset/collation name, uppercase with underscores: charset: 'UTF8MB4_UNICODE_CI'.
  2. Omit charset to accept the default UTF8MB4_UNICODE_CI (connection_config.js:176).
  3. Confirm the name with SHOW COLLATION on the target server.

Example fix

// before
createConnection({ charset: 'utf-8' });

// after
createConnection({ charset: 'UTF8MB4_UNICODE_CI' });
Defensive patterns

Strategy: validation

Validate before calling

const mysql = require('mysql2');
const { Charsets } = mysql; // or import constants
function assertCharset(name) {
  if (name && !Object.prototype.hasOwnProperty.call(require('mysql2/lib/constants/charsets'), name.toUpperCase())) {
    throw new TypeError(`Unsupported MySQL charset: ${name}`);
  }
}

Type guard

const isKnownCharset = (name, charsets) => Object.prototype.hasOwnProperty.call(charsets, String(name).toUpperCase());

Prevention

When it happens

Trigger: Passing charset: 'utf-8' or 'utf8mb4_general_ci' with a typo; using an IANA charset name instead of a MySQL charset name; a charset removed or renamed in the server version.

Common situations: Copy from HTML/HTTP charset strings (utf-8) instead of MySQL names; case/underscore mismatch (utf8mb4-unicode-ci vs UTF8MB4_UNICODE_CI — underscore form is required); referring to a collation that exists on a newer server only.

Related errors


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

Appendix: source

Thrown at lib/connection_config.js:259

      'MULTI_RESULTS',
      'TRANSACTIONS',
      'SESSION_TRACK',
      'CONNECT_ATTRS',
      'CLIENT_QUERY_ATTRIBUTES',
    ];
    if (options && options.multipleStatements) {
      defaultFlags.push('MULTI_STATEMENTS');
    }
    defaultFlags.push('PLUGIN_AUTH');
    defaultFlags.push('PLUGIN_AUTH_LENENC_CLIENT_DATA');

    return defaultFlags;
  }

  static getCharsetNumber(charset) {
    const num = Charsets[charset.toUpperCase()];
    if (num === undefined) {
      throw new TypeError(`Unknown charset '${charset}'`);
    }
    return num;
  }

  static getSSLProfile(name) {
    if (!SSLProfiles) {
      SSLProfiles = require('./constants/ssl_profiles.js');
    }
    const ssl = SSLProfiles[name];
    if (ssl === undefined) {
      throw new TypeError(`Unknown SSL profile '${name}'`);
    }
    return ssl;
  }

  static parseUrl(url) {
    const parsedUrl = new URL(url);
    const options = {

View on GitHub (pinned to 8b1f829d37)