{"id":13761,"library":"pg-native","title":"pg-native: PostgreSQL Native Bindings","description":"`pg-native` provides high-performance native bindings for Node.js to PostgreSQL, leveraging the `libpq` C library for direct communication. As of version 3.7.0, it offers both asynchronous (callback-based) and synchronous API operations. Its key differentiators include superior performance compared to pure JavaScript alternatives, owing to its native implementation, and the unique provision of synchronous database interactions. While synchronous operations can be convenient for scripting or application bootstrapping, they are generally discouraged for non-blocking server environments due to their blocking nature. `pg-native` is part of the broader `node-postgres` ecosystem but requires `libpq` to be installed on the host system for compilation and runtime. The project demonstrates a healthy release cadence and active maintenance, with recent updates and community interaction.","status":"active","version":"3.7.0","language":"javascript","source_language":"en","source_url":"https://github.com/brianc/node-postgres","tags":["javascript","postgres","pg","libpq"],"install":[{"cmd":"npm install pg-native","lang":"bash","label":"npm"},{"cmd":"yarn add pg-native","lang":"bash","label":"yarn"},{"cmd":"pnpm add pg-native","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides the underlying C/C++ native bindings to the PostgreSQL libpq client library.","package":"node-libpq","optional":false},{"reason":"Required system-level libraries for `pg-native` to compile and function, providing `pg_config` and `libpq`.","package":"PostgreSQL client libraries (e.g., libpq-dev)","optional":false}],"imports":[{"note":"pg-native is primarily designed for CommonJS (`require`). Direct ESM `import` syntax is not officially supported and can cause resolution issues in bundlers or ESM-only environments, as it's a native module.","wrong":"import { Client } from 'pg-native';","symbol":"Client","correct":"const Client = require('pg-native');"},{"note":"While `pg-native` can be required directly, it's often consumed via the `pg` package's `.native` property, which handles its lazy loading and API normalization. Direct access to `pg.native` for `Client` is preferred.","wrong":"const Client = require('pg').native;","symbol":"Client (via pg main package)","correct":"const { native } = require('pg');\nconst { Client } = native;"}],"quickstart":{"code":"const Client = require('pg-native');\n\nconst client = new Client();\nclient.connect(process.env.PG_CONNECTION_STRING ?? 'postgresql://user:password@localhost:5432/database', function(err) {\n  if(err) {\n    console.error('Connection error:', err.message);\n    return;\n  }\n  console.log('Connected to PostgreSQL database.');\n\n  // Text queries\n  client.query('SELECT NOW() AS the_date', function(err, rows) {\n    if(err) throw err;\n    console.log('Current date:', rows[0].the_date);\n\n    // Parameterized statements\n    client.query('SELECT $1::text as twitter_handle', ['@briancarlson'], function(err, rows) {\n      if(err) throw err;\n      console.log('Twitter handle:', rows[0].twitter_handle);\n    });\n  });\n\n  // Using prepared statements\n  client.prepare('get_twitter', 'SELECT $1::text as twitter_handle', 1, function(err) {\n    if(err) throw err;\n    client.execute('get_twitter', ['@briancarlson'], function(err, rows) {\n      if(err) throw err;\n      console.log('Prepared statement result 1:', rows[0].twitter_handle);\n\n      client.execute('get_twitter', ['@realcarrotfacts'], function(err, rows) {\n        if(err) throw err;\n        console.log('Prepared statement result 2:', rows[0].twitter_handle);\n        client.end(function() {\n          console.log('Client ended connection.');\n        });\n      });\n    });\n  });\n});","lang":"javascript","description":"This example demonstrates how to establish an asynchronous connection to a PostgreSQL database using `pg-native`, execute basic text queries, parameterized statements, and prepared statements, ensuring proper error handling and client termination."},"warnings":[{"fix":"Before installing `pg-native` via npm, ensure your operating system has the necessary PostgreSQL client development packages. Examples: `apt-get install libpq-dev python3 g++ make` (Debian/Ubuntu), `brew install libpq` (macOS), `yum install postgresql-devel` (RHEL/CentOS).","message":"The `pg-native` package requires specific PostgreSQL client libraries (like `libpq-dev`) to be pre-installed on the system for successful compilation and runtime. Installation will fail with an error code 1 if these dependencies are missing, impacting environments like Docker images without proper setup.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"For server-side applications, always prefer the asynchronous API (`client.connect`, `client.query`, etc.) to maintain non-blocking I/O. Reserve synchronous methods for utilities, scripts, or application bootstrapping where blocking is acceptable.","message":"Using synchronous methods like `connectSync`, `querySync`, and `executeSync` in `pg-native` can block the Node.js event loop, leading to performance issues and unresponsiveness in non-blocking environments like web servers.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Check the `pg-native` and `node-libpq` GitHub repositories for compatibility updates with new Node.js releases. A workaround might involve overriding `nan` peer dependencies in your `package.json` to a compatible version (e.g., `\"nan\": \"2.22.0\"` for Node.js 23).","message":"There have been instances where `pg-native` might not work correctly with newer Node.js versions due to dependencies like `nan`. For example, `pg-native` failed on Node.js 23 because `node-libpq` depended on `nan` 2.19.0, which didn't officially support Node.js 23.","severity":"breaking","affected_versions":">=3.x for Node.js versions >22"},{"fix":"Configure your bundler to mark `pg-native` as external. For example, in esbuild, use `external: ['pg-native']`. If using the main `pg` package, `pg.native` will return `null` if the native bindings are not found, allowing graceful fallback in some scenarios.","message":"When bundling applications (e.g., with esbuild or for serverless deployments like AWS Lambda), `pg-native` can cause resolution errors because it's a native module and often a lazy `require` dependency of the main `pg` package.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"search_vec":"'3.7.0':31 'activ':127 'altern':53 'api':41 'applic':76 'asynchron':35 'base':38 'bind':6,15 'block':85,91 'bootstrap':77 'broader':100 'c':23 'cadenc':125 'callback':37 'callback-bas':36 'communic':27 'communiti':133 'compar':49 'compil':116 'conveni':72 'databas':65 'demonstr':121 'differenti':45 'direct':26 'discourag':81 'due':88 'ecosystem':104 'environ':87 'general':80 'healthi':123 'high':12 'high-perform':11 'host':113 'implement':58 'includ':46 'instal':110 'interact':66,134 'javascript':52,135 'key':44 'leverag':20 'libpq':22,107,138 'librari':24 'mainten':128 'nativ':3,5,9,14,57,95 'natur':92 'node':102 'node-postgr':101 'node.js':17 'non':84 'non-block':83 'offer':33 'oper':42,69 'owe':54 'part':97 'perform':13,48 'pg':2,8,94,137 'pg-nativ':1,7,93 'postgr':103,136 'postgresql':4,19 'project':120 'provid':10 'provis':62 'pure':51 'recent':130 'releas':124 'requir':106 'runtim':118 'script':74 'server':86 'superior':47 'synchron':40,64,68 'system':114 'uniqu':61 'updat':131 'version':30","created_at":"2026-04-20T01:56:10.408399+00:00","updated_at":"2026-04-20T01:56:10.408399+00:00","problems":[{"fix":"Install the required system dependencies using your operating system's package manager: `sudo apt-get install libpq-dev python3 g++ make` (Debian/Ubuntu), `brew install libpq` (macOS), `sudo yum install postgresql-devel` (RHEL/CentOS).","cause":"PostgreSQL client development libraries (e.g., `libpq-dev`) are missing on the system, preventing `pg-native` from compiling its native bindings.","error":"npm ERR! code 1\nnpm ERR! Failed at the pg-native@X.Y.Z install script."},{"fix":"Ensure your connection string (e.g., `postgresql://user:password@host:port/database`) includes all necessary credentials and parameters, or that environment variables (like `PGUSER`, `PGPASSWORD`) are set, and the PostgreSQL server is configured to allow connections from your application.","cause":"The PostgreSQL connection string is missing required authentication parameters (e.g., username, password, host, database name) or the server is not configured to accept the connection.","error":"Client.connect: connection failed: fe_sendauth: no password supplied"},{"fix":"Mark `pg-native` as an external dependency in your bundler configuration. For esbuild, add `external: ['pg-native']` to your build options. This ensures `pg-native` is not included in the bundle and is resolved at runtime.","cause":"A bundler (like esbuild) is attempting to package `pg-native`, but it's a native module and cannot be bundled this way. It's often required lazily by `pg`.","error":"ERROR: Could not resolve \"pg-native\" (in bundler output or serverless logs)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/brianc/node-postgres","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/pg-native","openapi_spec":null,"status_page":null,"smithery":null,"categories":["database"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}