parse-db-url
The `parse-db-url` library is a specialized utility designed to accurately parse database connection URLs into structured configuration objects. Unlike Node.js's built-in `url.parse`, this package understands common conventions associated with various database drivers, such as 'postgres' or 'mysql', and intelligently extracts components like the adapter, host, port, database name, username, and password. A key feature is its ability to handle query-string parameters that can override earlier parts of the URL, offering flexible configuration options. The current stable version is 2.3.0. As a domain-specific parsing tool, its release cadence is slow, with the last publish being over five years ago, indicating a stable, feature-complete state primarily in maintenance mode, rather than active development. It provides a consistent interface for abstracting database connection details, simplifying multi-database application setups.
Common errors
-
ReferenceError: require is not defined in ES module scope
cause Attempting to use `require()` syntax in a JavaScript file that is being treated as an ES Module (e.g., via `"type": "module"` in `package.json` or `.mjs` extension).fixUse the ESM import syntax: `import parseDbUrl from 'parse-db-url';`. If you need to stay in CommonJS, ensure your file is `.js` and `"type": "module"` is not set, or it's within a CJS-specific directory. -
Parsed database configuration is incorrect or inconsistent (e.g., password missing, host is part of the password)
cause Special characters (like `@`, `:`, `/`, `?`, `#`) in the username or password portion of the database URL are not properly URL-encoded, causing the URL parser to misinterpret the segments.fixEnsure that any special characters in the username or password are correctly URL-encoded. For example, a password like `p@ss/word` should be `p%40ss%2Fword` in the URL. Use `encodeURIComponent()` for programmatic URL construction. -
TypeError: parseDbUrl is not a function
cause The module was imported incorrectly, perhaps attempting a named import for a default CommonJS export, or `require()` was used on a non-existent module.fixFor CommonJS, use `const parseDbUrl = require('parse-db-url');`. For ESM, use `import parseDbUrl from 'parse-db-url';`. Double-check the package name is exactly `parse-db-url`.
Warnings
- gotcha Database passwords containing special characters (e.g., '/', '#', '?', '@') may not be parsed correctly, leading to inconsistent or incorrect configuration objects. Always URL-encode special characters in passwords within the URL string if issues arise.
- gotcha The library does not validate if the specified database 'driver' or 'adapter' in the URL corresponds to an existing or supported database type. It extracts the string as provided, leaving validation to the consuming application.
- gotcha The `parse-db-url` package is built on Node.js's internal `url` module. While it adds database-specific logic, it may inherit parsing quirks or security considerations from the underlying URL parser. Always treat URLs from untrusted sources with caution to prevent potential SSRF, injection, or misinterpretation issues.
- breaking No explicit major breaking changes have been documented for versions within the 2.x range, nor are there readily available details for breaking changes between a hypothetical v1 and the current v2.3.0 in public resources. The package's stable state suggests minimal API evolution.
Install
-
npm install parse-db-url -
yarn add parse-db-url -
pnpm add parse-db-url
Imports
- parseDbUrl
import parseDbUrl from 'parse-db-url';
const parseDbUrl = require('parse-db-url'); - DBConfig
/** @typedef {ReturnType<typeof import('parse-db-url')>} DBConfig */
Quickstart
import parseDbUrl from 'parse-db-url';
const databaseUrl = process.env.DATABASE_URL ?? 'postgres://user:password@host:5432/mydb?ssl=true';
try {
const dbConfig = parseDbUrl(databaseUrl);
console.log('Parsed database configuration:');
console.log(` Adapter: ${dbConfig.adapter}`);
console.log(` Host: ${dbConfig.host}`);
console.log(` Port: ${dbConfig.port}`);
console.log(` Database: ${dbConfig.database}`);
console.log(` User: ${dbConfig.user}`);
// console.log(` Password: ${dbConfig.password ? '****' : 'N/A'}`); // Be cautious with logging credentials
// Example usage with a different URL format
const sqliteUrl = 'sqlite:///path/to/my.db';
const sqliteConfig = parseDbUrl(sqliteUrl);
console.log('\nParsed SQLite configuration:');
console.log(` Adapter: ${sqliteConfig.adapter}`);
console.log(` Database: ${sqliteConfig.database}`);
} catch (error) {
console.error('Error parsing database URL:', error.message);
process.exit(1);
}