{"id":"133a97a2b0f89501","repo":"mongodb/node-mongodb-native","slug":"invalid-port-zero-with-hostname","errorCode":null,"errorMessage":"Invalid port (zero) with hostname","messagePattern":"Invalid port \\(zero\\) with hostname","errorType":"exception","errorClass":"MongoParseError","httpStatus":null,"severity":"error","filePath":"src/utils.ts","lineNumber":920,"sourceCode":"\n    let normalized = decodeURIComponent(hostname).toLowerCase();\n    if (normalized.startsWith('[') && normalized.endsWith(']')) {\n      this.isIPv6 = true;\n      normalized = normalized.substring(1, hostname.length - 1);\n    }\n\n    this.host = normalized.toLowerCase();\n\n    if (typeof port === 'number') {\n      this.port = port;\n    } else if (typeof port === 'string' && port !== '') {\n      this.port = Number.parseInt(port, 10);\n    } else {\n      this.port = 27017;\n    }\n\n    if (this.port === 0) {\n      throw new MongoParseError('Invalid port (zero) with hostname');\n    }\n    Object.freeze(this);\n  }\n\n  [Symbol.for('nodejs.util.inspect.custom')](): string {\n    return this.inspect();\n  }\n\n  inspect(): string {\n    return `new HostAddress('${this.toString()}')`;\n  }\n\n  toString(): string {\n    if (typeof this.host === 'string') {\n      if (this.isIPv6) {\n        return `[${this.host}]:${this.port}`;\n      }\n      return `${this.host}:${this.port}`;","sourceCodeStart":902,"sourceCodeEnd":938,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/utils.ts#L902-L938","documentation":"Thrown by the HostAddress constructor when the parsed port of a connection-string host is exactly 0. Port 0 is not a usable client port (it means 'assign me one' for listeners), so the driver rejects it during connection-string parsing as a MongoParseError. Every other missing/blank port defaults to 27017; only an explicit :0 triggers this.","triggerScenarios":"A URI of the form `mongodb://host:0/` or `mongodb+srv://host:0/`, or programmatically constructing `new HostAddress('host:0')` / `HostAddress.fromHostPort('host', 0)`.","commonSituations":"Typo in the connection string; a config templating step that interpolates an unset PORT variable as 0; copying a server-side bind port (where 0 means ephemeral) into a client URI.","solutions":["Remove `:0` from the connection string and let it default to 27017, or specify a real port (e.g. :27017).","Ensure the PORT env var used to build the URI is set to a positive integer (1-65535) and never falls back to 0.","Validate the parsed URI with a check that the port is a positive integer before constructing the MongoClient."],"exampleFix":"// before\nconst uri = `mongodb://${HOST}:${process.env.PORT || 0}/`; // :0 => MongoParseError\nconst client = new MongoClient(uri);\n\n// after\nconst port = Number(process.env.PORT) || 27017;\nif (!(port > 0 && port < 65536)) throw new Error(`Invalid port: ${port}`);\nconst client = new MongoClient(`mongodb://${HOST}:${port}/`);","handlingStrategy":"validation","validationCode":"function buildUri(host: string, portEnv?: string): string {\n  const port = portEnv != null && portEnv !== '' ? Number(portEnv) : 27017;\n  if (!Number.isInteger(port) || port <= 0 || port > 65535) {\n    throw new Error(`Invalid MongoDB port: ${portEnv}`);\n  }\n  return `mongodb://${host}:${port}/`;\n}","typeGuard":"function isValidPort(p: unknown): p is number {\n  return typeof p === 'number' && Number.isInteger(p) && p > 0 && p < 65536;\n}","tryCatchPattern":null,"preventionTips":["Never fall back to port 0 for a client URI; default to 27017.","Parse and validate the connection string with URL before constructing MongoClient.","Keep server-bind port config separate from client URI port config."],"tags":["connection-string","configuration","validation"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}