mongodb/node-mongodb-native · error · MongoParseError
Invalid port (zero) with hostname
Error message
Invalid port (zero) with hostname
What it means
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.
Source
Thrown at src/utils.ts:920
let normalized = decodeURIComponent(hostname).toLowerCase();
if (normalized.startsWith('[') && normalized.endsWith(']')) {
this.isIPv6 = true;
normalized = normalized.substring(1, hostname.length - 1);
}
this.host = normalized.toLowerCase();
if (typeof port === 'number') {
this.port = port;
} else if (typeof port === 'string' && port !== '') {
this.port = Number.parseInt(port, 10);
} else {
this.port = 27017;
}
if (this.port === 0) {
throw new MongoParseError('Invalid port (zero) with hostname');
}
Object.freeze(this);
}
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}
inspect(): string {
return `new HostAddress('${this.toString()}')`;
}
toString(): string {
if (typeof this.host === 'string') {
if (this.isIPv6) {
return `[${this.host}]:${this.port}`;
}
return `${this.host}:${this.port}`;View on GitHub (pinned to 3366c21a63)
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.
Example fix
// before
const uri = `mongodb://${HOST}:${process.env.PORT || 0}/`; // :0 => MongoParseError
const client = new MongoClient(uri);
// after
const port = Number(process.env.PORT) || 27017;
if (!(port > 0 && port < 65536)) throw new Error(`Invalid port: ${port}`);
const client = new MongoClient(`mongodb://${HOST}:${port}/`); Defensive patterns
Strategy: validation
Validate before calling
function buildUri(host: string, portEnv?: string): string {
const port = portEnv != null && portEnv !== '' ? Number(portEnv) : 27017;
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
throw new Error(`Invalid MongoDB port: ${portEnv}`);
}
return `mongodb://${host}:${port}/`;
} Type guard
function isValidPort(p: unknown): p is number {
return typeof p === 'number' && Number.isInteger(p) && p > 0 && p < 65536;
} Prevention
- 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.
When it happens
Trigger: A URI of the form `mongodb://host:0/` or `mongodb+srv://host:0/`, or programmatically constructing `new HostAddress('host:0')` / `HostAddress.fromHostPort('host', 0)`.
Common situations: 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.
Related errors
- Missing required option `keyVaultNamespace`
- Invalid CANONICALIZE_HOST_NAME value: ${canonicalization}
- TOKEN_RESOURCE must be set in the auth mechanism properties
- User provided OIDC callbacks must return a valid object with
- TOKEN_RESOURCE must be set in the auth mechanism properties
AI-assisted analysis of mongodb/node-mongodb-native@3366c21a63 (2026-08-04).
Data as JSON: /data/errors/133a97a2b0f89501.json.
Report an issue: GitHub.