Database Connection String with Credentials Regex for JavaScript
/^(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|mssql|sqlserver|mariadb|oracle):\/\/([^:]+):([^@]+)@([^/?]+)(?:\/([^?]+))?(?:\?(.+))?$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching database connection string with credentials, ported and verified for JavaScript. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your JavaScript project — whether you're validating in an Express middleware, a Next.js API route, or a client-side form.
Javascript Implementation
// Database Connection String with Credentials
// ReDoS-safe | RegexVault — Security > Secrets & Config
const databaseConnectionStringWithCredentialsRegex = /^(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|mssql|sqlserver|mariadb|oracle):\\/\\/([^:]+):([^@]+)@([^\/?]+)(?:\\/([^?]+))?(?:\?(.+))?$/i;
function validateDatabaseConnectionStringWithCredentials(input: string): boolean {
return databaseConnectionStringWithCredentialsRegex.test(input);
}
// Example
console.log(validateDatabaseConnectionStringWithCredentials("postgresql://user:password@localhost:5432/mydb")); // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
postgresql://user:password@localhost:5432/mydb | postgresql://localhost:5432/mydb |
mysql://root:secret@db.example.com/app | ftp://user:pass@host/path |
mongodb+srv://admin:P%40ssw0rd@cluster.example.net/prod | postgresql://user:@localhost/db |
When to use this pattern
This pattern is drawn from the Security > Secrets & Config category and carries a ReDoS-safe certification. That matters for JavaScript developers because especially critical in long-running Node.js event loops where a ReDoS vulnerability can block the entire process. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Connection strings in Heroku, Render, and Railway configs are often set as environment variables but may be hardcoded in old codebases or appear in error messages when logged. Never log connection strings.
Technical Notes
Capture groups: 1=scheme, 2=username, 3=password, 4=host:port, 5=database, 6=query params. Passwords may be URL-encoded (e.g., P%40ssw0rd). Extract and rotate any credentials found in this format in code or config files.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern