mongodb/node-mongodb-native · error · MongoAPIError

Option "srvHost" must not be empty

Error message

Option "srvHost" must not be empty

What it means

Thrown by resolveSRVRecord() when handling a mongodb+srv:// URI and options.srvHost is not a string. srvHost is derived from the hostname portion of the URI during parsing; an empty or non-string value indicates the URI was malformed (no host after mongodb+srv://) or that srvHost was explicitly overridden to a non-string. It is a MongoAPIError raised before any DNS lookup.

Source

Thrown at src/connection_string.ts:79

        throw firstDNSError;
      }
    }
  };
}

const resolveSrv = retryDNSTimeoutFor('SRV');
const resolveTxt = retryDNSTimeoutFor('TXT');

/**
 * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal
 * connection string.
 *
 * @param uri - The connection string to parse
 * @param options - Optional user provided connection string options
 */
export async function resolveSRVRecord(options: MongoOptions): Promise<HostAddress[]> {
  if (typeof options.srvHost !== 'string') {
    throw new MongoAPIError('Option "srvHost" must not be empty');
  }

  // Asynchronously start TXT resolution so that we do not have to wait until
  // the SRV record is resolved before starting a second DNS query.
  const lookupAddress = options.srvHost;
  const txtResolutionPromise = resolveTxt(lookupAddress);

  txtResolutionPromise.then(undefined, squashError); // rejections will be handled later

  const hostname = `_${options.srvServiceName}._tcp.${lookupAddress}`;
  // Resolve the SRV record and use the result as the list of hosts to connect to.
  const addresses = await resolveSrv(hostname);

  if (addresses.length === 0) {
    throw new MongoAPIError('No addresses found at host');
  }

  for (const { name } of addresses) {

View on GitHub (pinned to 3366c21a63)

Solutions

  1. Verify the URI starts with mongodb+srv:// followed by a non-empty hostname.
  2. Fail fast at startup if !process.env.MONGODB_URI?.trim() and provide a clear message.
  3. Construct the URI with an explicit default host: `mongodb+srv://${host || 'cluster.example.net'}`.
  4. Inspect the URI string immediately before new MongoClient(uri) to confirm it has a host segment.

Example fix

// before
const uri = `mongodb+srv://${process.env.DB_HOST}`; // empty env -> 'mongodb+srv://'
// after
const host = process.env.DB_HOST;
if (!host) throw new Error('DB_HOST is required for mongodb+srv URI');
const uri = `mongodb+srv://${host}`;
Defensive patterns

Strategy: validation

Validate before calling

function buildSrvUri(host: string | undefined, dbName = 'test'): string {
  if (!host || typeof host !== 'string') {
    throw new Error('A non-empty host is required for mongodb+srv URIs');
  }
  return `mongodb+srv://${host}/${dbName}`;
}

Type guard

const isNonEmptyString = (v: unknown): v is string =>
  typeof v === 'string' && v.trim().length > 0;

Try / catch

try {
  await client.connect();
} catch (e) {
  if (e instanceof MongoAPIError && /srvHost" must not be empty/.test(e.message)) {
    throw new Error('MONGODB_URI is missing the SRV hostname');
  }
  throw e;
}

Prevention

When it happens

Trigger: A URI like 'mongodb+srv://' with no hostname; 'mongodb+srv:///dbname?...' ; constructing MongoOptions manually with srvHost unset; passing an empty string host through a custom URI builder.

Common situations: Building a connection string from an environment variable that is empty or unset; templating the host into the URI without a fallback; copy-paste truncating the hostname; SRV hostname coming from a secret/config map that resolved to empty.

Related errors


AI-assisted analysis of mongodb/node-mongodb-native@3366c21a63 (2026-08-04). Data as JSON: /data/errors/36e22c514325014a.json. Report an issue: GitHub.