mongodb-connection-string-url
A WhatWG URL-based TypeScript library for parsing, editing, and safely redacting MongoDB mongodb:// and mongodb+srv:// connection strings.
Repository Health
Technical Analysis
mongodb-connection-string-url gives MongoDB connection strings the same ergonomic, standards-based API that URL gives regular web addresses. Instead of hand-rolling regexes to pull apart a mongodb:// or mongodb+srv:// URI, you get a ConnectionString class built on the WhatWG URL API, with .searchParams, .pathname, and friends all working exactly as they do on a normal URL, plus the extra pieces a connection string actually needs: a .hosts list for multi-host deployments, an .isSRV flag, and case-insensitive query parameters, since MongoDB option names aren’t case-sensitive.
It also ships a dedicated redaction layer, redactConnectionString() and ConnectionString#redact(), purpose-built for the very common need to log or report a connection string without leaking credentials. This isn’t a side feature bolted onto a generic URL library — the parsing internals (adapted directly from the official MongoDB Node.js driver’s own connection-string handling) and the redaction rules (usernames, passwords, AWS session tokens, TLS key-file passwords, proxy credentials) are both written specifically for the mongodb:// connection-string spec, which is why the driver itself depends on this package rather than reimplementing the logic.
What You Get
- A
ConnectionStringclass that behaves like the standardURL/URLSearchParamsAPI, so existing WHATWG URL knowledge transfers directly - A
.hostsarray and.isSRVflag that correctly model MongoDB’s multi-host, non-standard-port connection strings, which a plainURLcannot represent - Case-insensitive
searchParamshandling, matching the MongoDB connection-string spec’s option-name rules - Built-in
.clone()for producing an independent copy of a parsed connection string - One-call redaction via
redactConnectionString(uri)orconnectionString.redact(), covering usernames, passwords, AWS session tokens, TLS key-file passwords, and proxy credentials - Strict TypeScript types, including
never-typed host/hostname/port accessors that make invalid single-host usage a compile-time error
Common Use Cases
- Validating and normalizing a user- or config-supplied MongoDB connection string before handing it to a driver
- Safely logging or displaying connection strings in CLIs, dashboards, or error messages without exposing credentials
- Programmatically rewriting connection-string parameters (e.g. adding
readPreferenceorauthMechanismProperties) without string concatenation - Detecting whether a given URI is an SRV-style (
mongodb+srv://) connection string that needs DNS seed-list resolution - Building developer tools (GUIs, CLIs, migration scripts) that need to inspect or manipulate MongoDB connection strings reliably
Under The Hood
Architecture
The library exports a single ConnectionString class (src/index.ts) that extends the WHATWG URL implementation from the whatwg-url package, plus a companion redact.ts module with free functions (redactValidConnectionString, redactConnectionString) that operate on ConnectionString instances or raw strings. Parsing works by regex-matching the URI into protocol/username/password/hosts/rest groups (HOSTS_REGEX, adapted directly from the official MongoDB Node.js driver’s own connection-string code), substituting a placeholder hostname so the underlying URL parser — which doesn’t understand multi-host mongodb:// URIs — can still validate and serialize everything else, then swapping the placeholder back out in toString(). The host/hostname/port getters are overridden to throw or return dummy values, since a MongoDB URI has a host list rather than a single host, tracked separately in _hosts. The class also swaps the searchParams prototype for a case-insensitive variant so option lookups match the spec. There’s no dependency injection or app lifecycle to speak of — it’s a self-contained parsing layer whose main external coupling is that MongoDB’s own Node.js driver imports this package directly, so its constructor and getters are effectively a stable contract.
Tech Stack
Written in TypeScript 5.9, compiled via tsc to CommonJS plus an ESM wrapper generated with gen-esm-wrapper, giving dual CJS/ESM exports. The only runtime dependency is whatwg-url (plus its types), used in place of Node’s built-in url module for consistent parsing behavior across Node and bundled/browser environments. Testing runs on Mocha, Chai, and ts-node/register, with tsd providing compile-time type-definition tests and nyc for coverage. Linting uses ESLint 9 with typescript-eslint, import/node/promise plugins, and Prettier. CI workflows run lint and test suites on every change, and a release-please-based workflow automates versioned releases and changelog generation. The package requires Node >=20.19 and has no database or web-framework dependencies — it’s a pure parsing library.
Code Quality
The test suite is large and thorough, with parametrized tables covering valid and invalid URI shapes, SRV variants, and edge cases like unescaped @ in passwords, empty userinfo sections, illegal characters, multi-host lists, and port handling — this is a well-exercised library rather than one with minimal smoke tests. Errors are typed (MongoParseError extends Error) and thrown with descriptive messages rather than swallowed. Naming is consistent and self-documenting, and type safety is strict throughout: TypeScript strict mode is enabled, generics back the record and typed-search-params helpers, and host/hostname/port accessors are deliberately typed as never to catch invalid single-host usage at compile time even though the underlying JS getters can’t throw cleanly (a documented workaround for a known Node.js URL-subclassing limitation). CI enforces lint, typecheck, and test on every change.
API Design
The public API is deliberately a drop-in extension of the standard URL API: new ConnectionString(uri) behaves like new URL(uri), so .searchParams, .pathname, and friends all work exactly as expected, and anyone already familiar with the WHATWG URL API already knows most of this library’s surface. On top of that it adds only the primitives a MongoDB URI actually needs and a vanilla URL can’t provide — .hosts, .isSRV, .clone(), and .redact() — each one mapped to an explicit, documented deviation from the URL spec in the README rather than left implicit. redactConnectionString(uri) offers a zero-instantiation convenience for the common “just get me a safe string to log” case, falling back to regex-based redaction if the URI doesn’t even parse. Getting started requires a single import and constructor call, and the README lists every intentional deviation from standard URL behavior explicitly.
Used by 2 apps in this directory
Countly
Analytics · Marketing
Privacy-first, self-hosted analytics and customer engagement platform with full data ownership, GDPR compliance, and AI-powered insights across mobile, web, desktop, and IoT.
Infisical
Security · Devops
The open-source platform for secrets, certificates, privileged access, and AI agent security — all in one self-hostable system.