Functions for dealing with a PostgreSQL connection string
npx @tessl/cli install tessl/npm-pg-connection-string@2.9.0PG Connection String is a library for parsing PostgreSQL connection strings into configuration objects compatible with the pg (node-postgres) client. It handles various connection string formats including TCP connections, UNIX domain sockets, SSL configurations, and query parameters, providing seamless integration with PostgreSQL client applications.
npm install pg-connection-stringimport { parse, toClientConfig, parseIntoClientConfig } from "pg-connection-string";For CommonJS:
const { parse, toClientConfig, parseIntoClientConfig } = require("pg-connection-string");Default import (CommonJS only):
const parse = require("pg-connection-string");
// Access other functions as: parse.toClientConfig, parse.parseIntoClientConfigimport { parse, parseIntoClientConfig } from "pg-connection-string";
// Basic parsing
const config = parse("postgres://user:password@localhost:5432/mydb");
console.log(config);
// { user: 'user', password: 'password', host: 'localhost', port: '5432', database: 'mydb' }
// Parse directly to pg.Client-compatible format
const clientConfig = parseIntoClientConfig("postgres://user:password@localhost:5432/mydb?ssl=true");
console.log(clientConfig.port); // 5432 (number, not string)
// UNIX domain socket
const socketConfig = parse("socket:/var/run/postgresql/?db=mydb");
console.log(socketConfig);
// { host: '/var/run/postgresql/', database: 'mydb' }Parses PostgreSQL connection strings into configuration objects, handling various formats and connection types.
/**
* Parse a PostgreSQL connection string into a configuration object
* @param connectionString - The connection string to parse
* @param options - Optional parsing options
* @returns Configuration object with connection parameters
*/
function parse(connectionString: string, options?: Options): ConnectionOptions;
interface Options {
/** Use libpq semantics when interpreting the connection string */
useLibpqCompat?: boolean;
}Converts connection configuration to be compatible with the pg.Client interface, with proper type conversion and validation.
/**
* Convert ConnectionOptions to pg.ClientConfig format
* @param config - Connection configuration object
* @returns ClientConfig compatible with pg.Client
*/
function toClientConfig(config: ConnectionOptions): ClientConfig;
/**
* Parse connection string directly to pg.ClientConfig format
* @param connectionString - The connection string to parse
* @returns ClientConfig compatible with pg.Client
*/
function parseIntoClientConfig(connectionString: string): ClientConfig;Standard PostgreSQL connection URLs with optional authentication and query parameters:
// Basic format
const config = parse("postgres://user:password@host:port/database");
// With query parameters
const config = parse("postgres://user:pass@host:5432/db?ssl=true&application_name=MyApp");
// URL-encoded special characters
const config = parse("postgres://user:my%20password@host/my%20database");Socket connections for local PostgreSQL servers:
// Simple socket path
const config = parse("/var/run/postgresql");
// Socket with database specification
const config = parse("/var/run/postgresql mydb");
// Full socket URL format
const config = parse("socket://user:pass@/var/run/postgresql/?db=mydb&encoding=utf8");SSL settings through connection string parameters:
// Boolean SSL
const config = parse("postgres://host/db?ssl=true");
const config = parse("postgres://host/db?ssl=false");
// SSL modes
const config = parse("postgres://host/db?sslmode=require");
const config = parse("postgres://host/db?sslmode=verify-full");
// SSL certificates (file paths)
const config = parse("postgres://host/db?sslcert=/path/cert.pem&sslkey=/path/key.pem");interface ConnectionOptions {
/** PostgreSQL server hostname or UNIX socket path */
host: string | null;
/** Authentication password */
password?: string;
/** Authentication username */
user?: string;
/** Server port (as string) */
port?: string | null;
/** Database name */
database: string | null | undefined;
/** Client character encoding */
client_encoding?: string;
/** SSL configuration - boolean, string, or object */
ssl?: boolean | string | SSLConfig;
/** Application name for connection identification */
application_name?: string;
/** Fallback application name */
fallback_application_name?: string;
/** Additional connection options string */
options?: string;
/** TCP keepalive configuration */
keepalives?: number;
/** Additional query parameters are preserved */
[key: string]: unknown;
}
interface SSLConfig {
/** Certificate authority data */
ca?: string;
/** Client certificate data */
cert?: string | null;
/** Client private key data */
key?: string;
/** Whether to reject unauthorized certificates */
rejectUnauthorized?: boolean;
/** Custom server identity verification function (used in libpq-compatible modes) */
checkServerIdentity?: (() => void) | undefined;
}The library preserves and processes various query parameters:
true, false, 1, or 0 for boolean SSLdisable, prefer, require, verify-ca, verify-full, no-verify)ssl: false)ssl: true)ssl: { rejectUnauthorized: false })When useLibpqCompat: true or uselibpqcompat=true:
// Invalid port numbers throw errors
try {
const config = parseIntoClientConfig("postgres://host:invalid/db");
} catch (error) {
console.error(error.message); // "Invalid port: invalid"
}
// SSL security warnings for insecure configurations
try {
const config = parse("postgres://host/db?sslmode=verify-ca&uselibpqcompat=true");
} catch (error) {
console.error(error.message); // Security warning about missing CA certificate
}import { parse } from "pg-connection-string";
const config = parse("postgres://myuser:mypass@localhost:5432/mydb");
console.log(config);
// {
// user: 'myuser',
// password: 'mypass',
// host: 'localhost',
// port: '5432',
// database: 'mydb'
// }import { Client } from "pg";
import { parseIntoClientConfig } from "pg-connection-string";
const connectionString = "postgres://user:pass@localhost/mydb?ssl=true";
const clientConfig = parseIntoClientConfig(connectionString);
const client = new Client(clientConfig);
await client.connect();import { parse } from "pg-connection-string";
// Simple path format
const config1 = parse("/var/run/postgresql");
console.log(config1.host); // '/var/run/postgresql'
// With database
const config2 = parse("/var/run/postgresql myapp");
console.log(config2.host, config2.database); // '/var/run/postgresql', 'myapp'
// Full socket URL
const config3 = parse("socket://user:pass@/tmp/.s.PGSQL.5432/?db=mydb");
console.log(config3);
// { user: 'user', password: 'pass', host: '/tmp/.s.PGSQL.5432/', database: 'mydb' }import { parse } from "pg-connection-string";
const connectionString = "postgres://host/db?" +
"sslmode=verify-full&" +
"sslcert=/path/to/client.crt&" +
"sslkey=/path/to/client.key&" +
"sslrootcert=/path/to/ca.crt";
const config = parse(connectionString);
console.log(config.ssl);
// {
// cert: '...certificate content...',
// key: '...private key content...',
// ca: '...CA certificate content...'
// }