Skip to content

Repository files navigation

parse-connection-url

npm version CI npm provenance Node.js Version Zero Dependencies TypeScript License: MIT

One parser for every connection string. Parse URLs and config objects into a unified shape, then export to Knex, Sequelize, TypeORM, Prisma, MongoDB, Redis, and more. Zero runtime dependencies.

πŸ“š Full documentation β†’

Highlights

  • Parse anything β€” URL strings, config objects (with field aliases), jdbc:/odbc: connection strings, multi-host replica sets, IPv6 hosts, 60+ protocols with default ports
  • Round-trip safe β€” credentials stored decoded, URI-encoded only at serialization; parse β†’ toUrl() β†’ parse survives special characters
  • Export everywhere β€” toKnex, toSequelize, toTypeORM, toPrisma, toMongo, toRedis, toSolr, toHttpUrl
  • Safe to log β€” toJSON() masks passwords and sensitive query params (token, secret, …), so JSON.stringify(conn) never leaks
  • Typed errors β€” ParseError / ValidationError / ProtocolError with stable codes, plus Connection.isValid() for try/catch-free checks
  • Builder + immutable API β€” Connection.builder() and chainable with* methods
  • Trustworthy supply chain β€” zero dependencies, published with npm provenance via OIDC trusted publishing, tested on Linux/macOS/Windows Γ— Node 20/22/24

Installation

npm install parse-connection-url

Requires Node.js β‰₯ 18. TypeScript definitions included.

Quick start

const Connection = require('parse-connection-url')

const conn = new Connection('postgres://admin:s3cret@db.example.com:5433/orders?ssl=true')

conn.connection
// { protocol: 'postgres', hostname: 'db.example.com', port: 5433,
//   path: '/orders', params: { ssl: 'true' }, secure: false, ... }
conn.auth
// { username: 'admin', password: 's3cret' }

conn.toUrl()
// 'postgres://admin:s3cret@db.example.com:5433/orders?ssl=true'

Straight to your driver or ORM

const knex = require('knex')({ client: 'pg', connection: conn.toKnexConnection() })
const sequelize = new Sequelize(conn.toSequelize())
const dataSource = new DataSource({ ...conn.toTypeORM(), entities: [] })
const redis = createClient(new Connection(process.env.REDIS_URL).toRedis())

Config objects, env vars, validation

// Objects with common aliases (host/hostname, user/username, database/path, ...)
new Connection({ protocol: 'mysql', host: 'db', user: 'app', pass: 'pw', database: 'shop' })

// Environment variables
const conn = Connection.fromEnv('DATABASE_URL')        // throws if unset
const maybe = Connection.tryFromEnv('DATABASE_URL')    // null if unset

// Validation without try/catch
Connection.isValid('not a url') // false

Multi-host / replica sets

const rs = new Connection('mongodb://db1:27017,db2:27018,db3:27019/app?replicaSet=rs0')
rs.getHosts()      // [{ hostname: 'db1', port: 27017 }, ...]
rs.isReplicaSet()  // true
rs.toUrl()         // round-trips all hosts

Builder and immutable updates

const conn = Connection.builder()
  .protocol('postgres').host('db.example.com').database('orders')
  .user('admin').password('s3cret')
  .build()

const replica = conn.withHostname('replica.example.com').withParam('readonly', 'true')
// conn is unchanged β€” every with* method returns a new Connection

Safe logging

JSON.stringify(conn)
// password and sensitive query params masked with '***'

conn.toUrl() // ⚠️ real credentials β€” don't log this

Typed errors

try {
  new Connection(userInput)
} catch (err) {
  if (err instanceof Connection.ParseError) {
    // err.code === 'PARSE_ERROR', err.details.url
  }
}

Documentation

Getting started install, first parse, quick API tour
Parsing URLs, objects, multi-host, IPv6, jdbc/odbc, normalization
Exporters Knex, Sequelize, TypeORM, Prisma, Mongo, Redis, Solr recipes
Building & modifying builder, with*, params, fragments, hosts
Security & logging masking, encoding model, provenance
Error handling the error hierarchy and codes
Migrating to v2 breaking changes from 1.x
API reference every method and type

Support

Please open an issue. Security reports: see SECURITY.md.

Contributing

Contributions welcome! See CONTRIBUTING.md β€” note that commit messages follow Conventional Commits (enforced by commitlint) and releases are fully automated with semantic-release.

License

MIT Β© Jordan Dziat

About

A library to help parse out connection strings.

Resources

Contributing

Security policy

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages