or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# PG Connection String

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: pg-connection-string

7

- **Package Type**: npm

8

- **Language**: JavaScript with TypeScript definitions

9

- **Installation**: `npm install pg-connection-string`

10

11

## Core Imports

12

13

```typescript

14

import { parse, toClientConfig, parseIntoClientConfig } from "pg-connection-string";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { parse, toClientConfig, parseIntoClientConfig } = require("pg-connection-string");

21

```

22

23

Default import (CommonJS only):

24

25

```javascript

26

const parse = require("pg-connection-string");

27

// Access other functions as: parse.toClientConfig, parse.parseIntoClientConfig

28

```

29

30

## Basic Usage

31

32

```typescript

33

import { parse, parseIntoClientConfig } from "pg-connection-string";

34

35

// Basic parsing

36

const config = parse("postgres://user:password@localhost:5432/mydb");

37

console.log(config);

38

// { user: 'user', password: 'password', host: 'localhost', port: '5432', database: 'mydb' }

39

40

// Parse directly to pg.Client-compatible format

41

const clientConfig = parseIntoClientConfig("postgres://user:password@localhost:5432/mydb?ssl=true");

42

console.log(clientConfig.port); // 5432 (number, not string)

43

44

// UNIX domain socket

45

const socketConfig = parse("socket:/var/run/postgresql/?db=mydb");

46

console.log(socketConfig);

47

// { host: '/var/run/postgresql/', database: 'mydb' }

48

```

49

50

## Capabilities

51

52

### Connection String Parsing

53

54

Parses PostgreSQL connection strings into configuration objects, handling various formats and connection types.

55

56

```typescript { .api }

57

/**

58

* Parse a PostgreSQL connection string into a configuration object

59

* @param connectionString - The connection string to parse

60

* @param options - Optional parsing options

61

* @returns Configuration object with connection parameters

62

*/

63

function parse(connectionString: string, options?: Options): ConnectionOptions;

64

65

interface Options {

66

/** Use libpq semantics when interpreting the connection string */

67

useLibpqCompat?: boolean;

68

}

69

```

70

71

### Client Configuration Conversion

72

73

Converts connection configuration to be compatible with the pg.Client interface, with proper type conversion and validation.

74

75

```typescript { .api }

76

/**

77

* Convert ConnectionOptions to pg.ClientConfig format

78

* @param config - Connection configuration object

79

* @returns ClientConfig compatible with pg.Client

80

*/

81

function toClientConfig(config: ConnectionOptions): ClientConfig;

82

83

/**

84

* Parse connection string directly to pg.ClientConfig format

85

* @param connectionString - The connection string to parse

86

* @returns ClientConfig compatible with pg.Client

87

*/

88

function parseIntoClientConfig(connectionString: string): ClientConfig;

89

```

90

91

## Connection String Formats

92

93

### TCP Connections

94

95

Standard PostgreSQL connection URLs with optional authentication and query parameters:

96

97

```typescript

98

// Basic format

99

const config = parse("postgres://user:password@host:port/database");

100

101

// With query parameters

102

const config = parse("postgres://user:pass@host:5432/db?ssl=true&application_name=MyApp");

103

104

// URL-encoded special characters

105

const config = parse("postgres://user:my%20password@host/my%20database");

106

```

107

108

### UNIX Domain Sockets

109

110

Socket connections for local PostgreSQL servers:

111

112

```typescript

113

// Simple socket path

114

const config = parse("/var/run/postgresql");

115

116

// Socket with database specification

117

const config = parse("/var/run/postgresql mydb");

118

119

// Full socket URL format

120

const config = parse("socket://user:pass@/var/run/postgresql/?db=mydb&encoding=utf8");

121

```

122

123

### SSL Configuration

124

125

SSL settings through connection string parameters:

126

127

```typescript

128

// Boolean SSL

129

const config = parse("postgres://host/db?ssl=true");

130

const config = parse("postgres://host/db?ssl=false");

131

132

// SSL modes

133

const config = parse("postgres://host/db?sslmode=require");

134

const config = parse("postgres://host/db?sslmode=verify-full");

135

136

// SSL certificates (file paths)

137

const config = parse("postgres://host/db?sslcert=/path/cert.pem&sslkey=/path/key.pem");

138

```

139

140

## Types

141

142

```typescript { .api }

143

interface ConnectionOptions {

144

/** PostgreSQL server hostname or UNIX socket path */

145

host: string | null;

146

/** Authentication password */

147

password?: string;

148

/** Authentication username */

149

user?: string;

150

/** Server port (as string) */

151

port?: string | null;

152

/** Database name */

153

database: string | null | undefined;

154

/** Client character encoding */

155

client_encoding?: string;

156

/** SSL configuration - boolean, string, or object */

157

ssl?: boolean | string | SSLConfig;

158

/** Application name for connection identification */

159

application_name?: string;

160

/** Fallback application name */

161

fallback_application_name?: string;

162

/** Additional connection options string */

163

options?: string;

164

/** TCP keepalive configuration */

165

keepalives?: number;

166

/** Additional query parameters are preserved */

167

[key: string]: unknown;

168

}

169

170

interface SSLConfig {

171

/** Certificate authority data */

172

ca?: string;

173

/** Client certificate data */

174

cert?: string | null;

175

/** Client private key data */

176

key?: string;

177

/** Whether to reject unauthorized certificates */

178

rejectUnauthorized?: boolean;

179

/** Custom server identity verification function (used in libpq-compatible modes) */

180

checkServerIdentity?: (() => void) | undefined;

181

}

182

```

183

184

## Query Parameters

185

186

The library preserves and processes various query parameters:

187

188

- **ssl**: Set to `true`, `false`, `1`, or `0` for boolean SSL

189

- **sslmode**: SSL mode (`disable`, `prefer`, `require`, `verify-ca`, `verify-full`, `no-verify`)

190

- **sslcert**: Path to client certificate file

191

- **sslkey**: Path to client private key file

192

- **sslrootcert**: Path to certificate authority file

193

- **application_name**: Application identifier

194

- **client_encoding**: Character encoding

195

- **host**: Override hostname from URL

196

- **uselibpqcompat**: Enable libpq-compatible SSL behavior

197

198

## SSL Mode Behaviors

199

200

### Standard SSL Modes

201

- **disable**: SSL disabled (`ssl: false`)

202

- **prefer/require/verify-ca/verify-full**: SSL enabled (`ssl: true`)

203

- **no-verify**: SSL with disabled certificate validation (`ssl: { rejectUnauthorized: false }`)

204

205

### LibPQ Compatible Modes

206

When `useLibpqCompat: true` or `uselibpqcompat=true`:

207

- **disable**: SSL disabled

208

- **prefer**: SSL with disabled certificate validation

209

- **require**: SSL with certificate validation (behaves like verify-ca if root cert provided)

210

- **verify-ca**: SSL with CA validation only

211

- **verify-full**: SSL with full certificate and identity validation

212

213

## Error Handling

214

215

```typescript

216

// Invalid port numbers throw errors

217

try {

218

const config = parseIntoClientConfig("postgres://host:invalid/db");

219

} catch (error) {

220

console.error(error.message); // "Invalid port: invalid"

221

}

222

223

// SSL security warnings for insecure configurations

224

try {

225

const config = parse("postgres://host/db?sslmode=verify-ca&uselibpqcompat=true");

226

} catch (error) {

227

console.error(error.message); // Security warning about missing CA certificate

228

}

229

```

230

231

## Usage Examples

232

233

### Basic Connection Parsing

234

235

```typescript

236

import { parse } from "pg-connection-string";

237

238

const config = parse("postgres://myuser:mypass@localhost:5432/mydb");

239

console.log(config);

240

// {

241

// user: 'myuser',

242

// password: 'mypass',

243

// host: 'localhost',

244

// port: '5432',

245

// database: 'mydb'

246

// }

247

```

248

249

### pg.Client Integration

250

251

```typescript

252

import { Client } from "pg";

253

import { parseIntoClientConfig } from "pg-connection-string";

254

255

const connectionString = "postgres://user:pass@localhost/mydb?ssl=true";

256

const clientConfig = parseIntoClientConfig(connectionString);

257

258

const client = new Client(clientConfig);

259

await client.connect();

260

```

261

262

### UNIX Socket Connection

263

264

```typescript

265

import { parse } from "pg-connection-string";

266

267

// Simple path format

268

const config1 = parse("/var/run/postgresql");

269

console.log(config1.host); // '/var/run/postgresql'

270

271

// With database

272

const config2 = parse("/var/run/postgresql myapp");

273

console.log(config2.host, config2.database); // '/var/run/postgresql', 'myapp'

274

275

// Full socket URL

276

const config3 = parse("socket://user:pass@/tmp/.s.PGSQL.5432/?db=mydb");

277

console.log(config3);

278

// { user: 'user', password: 'pass', host: '/tmp/.s.PGSQL.5432/', database: 'mydb' }

279

```

280

281

### SSL Certificate Configuration

282

283

```typescript

284

import { parse } from "pg-connection-string";

285

286

const connectionString = "postgres://host/db?" +

287

"sslmode=verify-full&" +

288

"sslcert=/path/to/client.crt&" +

289

"sslkey=/path/to/client.key&" +

290

"sslrootcert=/path/to/ca.crt";

291

292

const config = parse(connectionString);

293

console.log(config.ssl);

294

// {

295

// cert: '...certificate content...',

296

// key: '...private key content...',

297

// ca: '...CA certificate content...'

298

// }

299

```