{"id":"36e22c514325014a","repo":"mongodb/node-mongodb-native","slug":"option-srvhost-must-not-be-empty","errorCode":null,"errorMessage":"Option \"srvHost\" must not be empty","messagePattern":"Option \"srvHost\" must not be empty","errorType":"exception","errorClass":"MongoAPIError","httpStatus":null,"severity":"error","filePath":"src/connection_string.ts","lineNumber":79,"sourceCode":"        throw firstDNSError;\n      }\n    }\n  };\n}\n\nconst resolveSrv = retryDNSTimeoutFor('SRV');\nconst resolveTxt = retryDNSTimeoutFor('TXT');\n\n/**\n * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal\n * connection string.\n *\n * @param uri - The connection string to parse\n * @param options - Optional user provided connection string options\n */\nexport async function resolveSRVRecord(options: MongoOptions): Promise<HostAddress[]> {\n  if (typeof options.srvHost !== 'string') {\n    throw new MongoAPIError('Option \"srvHost\" must not be empty');\n  }\n\n  // Asynchronously start TXT resolution so that we do not have to wait until\n  // the SRV record is resolved before starting a second DNS query.\n  const lookupAddress = options.srvHost;\n  const txtResolutionPromise = resolveTxt(lookupAddress);\n\n  txtResolutionPromise.then(undefined, squashError); // rejections will be handled later\n\n  const hostname = `_${options.srvServiceName}._tcp.${lookupAddress}`;\n  // Resolve the SRV record and use the result as the list of hosts to connect to.\n  const addresses = await resolveSrv(hostname);\n\n  if (addresses.length === 0) {\n    throw new MongoAPIError('No addresses found at host');\n  }\n\n  for (const { name } of addresses) {","sourceCodeStart":61,"sourceCodeEnd":97,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/connection_string.ts#L61-L97","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Verify the URI starts with mongodb+srv:// followed by a non-empty hostname.","Fail fast at startup if !process.env.MONGODB_URI?.trim() and provide a clear message.","Construct the URI with an explicit default host: `mongodb+srv://${host || 'cluster.example.net'}`.","Inspect the URI string immediately before new MongoClient(uri) to confirm it has a host segment."],"exampleFix":"// before\nconst uri = `mongodb+srv://${process.env.DB_HOST}`; // empty env -> 'mongodb+srv://'\n// after\nconst host = process.env.DB_HOST;\nif (!host) throw new Error('DB_HOST is required for mongodb+srv URI');\nconst uri = `mongodb+srv://${host}`;","handlingStrategy":"validation","validationCode":"function buildSrvUri(host: string | undefined, dbName = 'test'): string {\n  if (!host || typeof host !== 'string') {\n    throw new Error('A non-empty host is required for mongodb+srv URIs');\n  }\n  return `mongodb+srv://${host}/${dbName}`;\n}","typeGuard":"const isNonEmptyString = (v: unknown): v is string =>\n  typeof v === 'string' && v.trim().length > 0;","tryCatchPattern":"try {\n  await client.connect();\n} catch (e) {\n  if (e instanceof MongoAPIError && /srvHost\" must not be empty/.test(e.message)) {\n    throw new Error('MONGODB_URI is missing the SRV hostname');\n  }\n  throw e;\n}","preventionTips":["Fail fast at startup if the connection URI has no host.","Validate URI shape with new URL(uri) before passing to MongoClient.","Never template an unverified env var directly into the URI."],"tags":["connection-string","dns","srv","config"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}