or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-pg-connection-string

Functions for dealing with a PostgreSQL connection string

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/pg-connection-string@2.9.x

To install, run

npx @tessl/cli install tessl/npm-pg-connection-string@2.9.0

index.mddocs/

PG Connection String

PG 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.

Package Information

  • Package Name: pg-connection-string
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install pg-connection-string

Core Imports

import { 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.parseIntoClientConfig

Basic Usage

import { 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' }

Capabilities

Connection String Parsing

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;
}

Client Configuration Conversion

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;

Connection String Formats

TCP Connections

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");

UNIX Domain Sockets

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 Configuration

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");

Types

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;
}

Query Parameters

The library preserves and processes various query parameters:

  • ssl: Set to true, false, 1, or 0 for boolean SSL
  • sslmode: SSL mode (disable, prefer, require, verify-ca, verify-full, no-verify)
  • sslcert: Path to client certificate file
  • sslkey: Path to client private key file
  • sslrootcert: Path to certificate authority file
  • application_name: Application identifier
  • client_encoding: Character encoding
  • host: Override hostname from URL
  • uselibpqcompat: Enable libpq-compatible SSL behavior

SSL Mode Behaviors

Standard SSL Modes

  • disable: SSL disabled (ssl: false)
  • prefer/require/verify-ca/verify-full: SSL enabled (ssl: true)
  • no-verify: SSL with disabled certificate validation (ssl: { rejectUnauthorized: false })

LibPQ Compatible Modes

When useLibpqCompat: true or uselibpqcompat=true:

  • disable: SSL disabled
  • prefer: SSL with disabled certificate validation
  • require: SSL with certificate validation (behaves like verify-ca if root cert provided)
  • verify-ca: SSL with CA validation only
  • verify-full: SSL with full certificate and identity validation

Error Handling

// 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
}

Usage Examples

Basic Connection Parsing

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'
// }

pg.Client Integration

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();

UNIX Socket Connection

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' }

SSL Certificate Configuration

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...'
// }