npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

multi-connectionstring

v0.1.2

Published

Manage multiple connection strings with quick switching via API and CLI. Supports JSON/YAML/INI, environment overrides.

Downloads

16

Readme

multi-connectionstring

🧩 Manage multiple database connection strings from a single configuration file.
Switch easily between environments, clients, or databases — via CLI or Code.

npm version npm downloads GitHub release License: MIT


🚀 Features

  • 🔄 Switch between multiple connection strings (e.g. clients, environments)
  • 🗂️ Support for JSON, YAML, and INI config files
  • ⚙️ Environment variable override (DB_CLIENT, DBCONFIG_FILE)
  • 💻 Built-in CLI tool (mcs) for quick switching and inspection
  • 🧠 Simple JavaScript API for integration in any Node.js project
  • 📦 Minimal dependencies (yaml, ini, dotenv)
  • 🛠️ Works with any DB driver (PostgreSQL, MySQL, MSSQL, MongoDB, etc.)

⚠️ Security Notice

IMPORTANT: Configuration files contain sensitive connection strings with usernames and passwords.

Best practices:

  • Always add .dbconfig.* to your .gitignore
  • ✅ Never commit config files with real credentials to version control
  • ✅ Use environment variables for sensitive data in production
  • ✅ Consider using connection strings without embedded passwords (use cloud provider IAM authentication when possible)
  • ✅ Keep different configs for dev/staging/prod

Example .gitignore:

.dbconfig.json
.dbconfig.yaml
.dbconfig.yml
.dbconfig.ini
.env

🧑‍💻 Installation

npm install multi-connectionstring

This installs both the library (for programmatic use) and the CLI tool (mcs).


⚙️ Configuration file

Create a file in your project root named .dbconfig.json, or .dbconfig.yaml / .dbconfig.yml / .dbconfig.ini.

The file contains all your database connection strings and their parameters.

Example: JSON

{
  "clients": {
    "clientA": {
      "connectionString": "postgres://user:pass@hostA/dbA",
      "active": false
    },
    "clientB": {
      "connectionString": "postgres://user:pass@hostB/dbB",
      "active": true
    },
    "clientC": {
      "connectionString": "postgres://user:pass@hostC/dbC"
    }
  }
}

Example: YAML

clients:
  clientA:
    connectionString: postgres://user:pass@hostA/dbA
    active: false
  clientB:
    connectionString: postgres://user:pass@hostB/dbB
    active: true
  clientC:
    connectionString: postgres://user:pass@hostC/dbC

Example: INI

[clientA]
connectionString=postgres://user:pass@hostA/dbA
active=false

[clientB]
connectionString=postgres://user:pass@hostB/dbB
active=true

[clientC]
connectionString=postgres://user:pass@hostC/dbC

🧭 CLI Usage

After installing, you can use the mcs command directly in your terminal.

List all connection strings

mcs list

Example output:

  clientA         ->  postgres://user:pass@hostA/dbA
* clientB         ->  postgres://user:pass@hostB/dbB
  clientC         ->  postgres://user:pass@hostC/dbC

* = active connection

Show the active connection

mcs current

Example output:

Active connection:
clientB -> postgres://user:pass@hostB/dbB

Switch active connection

mcs use clientA

This updates the .dbconfig file by setting active: true for clientA and false for all others.

Output:

✓ Connection "clientA" is now active.

Help

mcs --help

💻 Usage

You can also use multi-connectionstring inside your Node.js code.

Import

const {
  getActiveConnection,
  setActiveConnection,
  listConnections,
  getConnectionByKey
} = require('multi-connectionstring');

Get the active connection

const active = getActiveConnection();
console.log(active.key, active.connectionString);
// Output: clientB postgres://user:pass@hostB/dbB

If DB_CLIENT is set in your environment, that key will be used. Otherwise, it returns the one marked active: true in the config file.

Returns: { key, connectionString, active, ...otherFields } or null if none active


Set a connection as active

setActiveConnection('clientC');
console.log('✓ Switched to clientC');

This updates the file, setting active=true for clientC.

Returns: true on success
Throws: Error if key doesn't exist or file issues


List all connections

const all = listConnections();
console.log(all);
// [
//   { key: 'clientA', connectionString: '...', active: false },
//   { key: 'clientB', connectionString: '...', active: true },
//   ...
// ]

Get a connection by key

const conn = getConnectionByKey('clientA');
if (conn) {
  console.log(conn.connectionString);
} else {
  console.log('Client not found');
}

Returns: Connection object or null if not found


🌱 Environment Variables

| Variable | Description | | ------------------- | --------------------------------------------------------------------- | | DB_CLIENT | Forces a specific connection key (runtime only, does not modify file) | | DBCONFIG_FILE | Custom path to your .dbconfig file | | .env | Automatically loaded if present (via dotenv) |

Example .env:

DB_CLIENT=clientB
DBCONFIG_FILE=./config/mydbconfig.yaml

🧩 Typical workflow

  1. Define all connection strings in .dbconfig.json
  2. Add .dbconfig.json to .gitignore
  3. Use mcs list to view them
  4. Switch quickly via mcs use clientB
  5. In your app, call getActiveConnection() to always get the current one

🔌 Example integration with database client

PostgreSQL (pg)

const { getActiveConnection } = require('multi-connectionstring');
const { Client } = require('pg');

(async () => {
  const active = getActiveConnection();
  
  if (!active) {
    console.error('No active connection configured');
    process.exit(1);
  }
  
  const client = new Client({ connectionString: active.connectionString });
  await client.connect();
  
  console.log('✓ Connected to', active.key);
  
  // Your queries here...
  const res = await client.query('SELECT NOW()');
  console.log(res.rows[0]);
  
  await client.end();
})();

MongoDB (mongoose)

const { getActiveConnection } = require('multi-connectionstring');
const mongoose = require('mongoose');

(async () => {
  const active = getActiveConnection();
  await mongoose.connect(active.connectionString);
  console.log('✓ Connected to MongoDB:', active.key);
})();

MySQL (mysql2)

const { getActiveConnection } = require('multi-connectionstring');
const mysql = require('mysql2/promise');

(async () => {
  const active = getActiveConnection();
  const connection = await mysql.createConnection(active.connectionString);
  console.log('✓ Connected to MySQL:', active.key);
})();

🧱 File resolution order

multi-connectionstring will look for configuration in this order:

  1. Path from DBCONFIG_FILE (if provided)
  2. .dbconfig.json
  3. .dbconfig.yaml / .dbconfig.yml
  4. .dbconfig.ini

If none is found, an error is thrown.


🔧 Error Handling

The package provides clear error messages for common issues:

try {
  const active = getActiveConnection();
  // Use connection...
} catch (err) {
  console.error('Error:', err.message);
  // Examples:
  // - Config file not found. Create .dbconfig.json...
  // - DB_CLIENT="invalid" does not match any client...
  // - Client "xyz" must be an object with at least a connectionString field
}

📝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.


🪪 License

MIT © 2025


💬 Support