node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

Connection Documentation: Peer Conncetion

Open jasper-lyons-rhul opened this issue 7 years ago • 1 comments

Hey! Thanks for your work on a great project.

I went looking for docs on how to manage postgresql's peer authentication. It's mentioned in https://github.com/brianc/node-postgres/issues/613 which provides a solution. Unfortunately that doesn't appear in the documentation. I wondered if we could add a section:

Password-less Authentication (Peer Auth)

Postgresql supports a number of authentication procedures which can be helpful, especially in development. One of those is Peer Authentication which allows the current OS user to authenticate with a local database. For this to work though, the connection need to be "local", specifically that means using a unix socket instead of a TCP socket.

To connect to the unix socket provided by postgresql you just need to use the path to the directory containing the socket as the host to your client configuration, this directory is commonly /var/run/postgresql. The client will then connect to the database mydb on the local postgresql server with the OS user that ran the program.

const { Pool, Client } = require('pg')

const pool = new Pool({
  host: '/var/run/postgresql',
  database: 'mydb'
})

pool.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  pool.end()
})

const client = new Client({
  host: '/var/run/postgresql',
  database: 'mydb'
})
client.connect()

client.query('SELECT NOW()', (err, res) => {
  console.log(err, res)
  pool.end()
})

jasper-lyons-rhul avatar Dec 27 '18 11:12 jasper-lyons-rhul

const { Pool, Client } = require('pg');

// For Pool connection const pool = new Pool({ host: '/var/run/postgresql', // Path to the directory containing the socket database: 'mydb', // Replace 'mydb' with your database name // additional configurations can be added here if needed });

pool.query('SELECT NOW()', (err, res) => { if (err) { console.error('Error executing query', err.stack); } else { console.log('Pool query result:', res); } pool.end(); // close the pool });

// For Client connection const client = new Client({ host: '/var/run/postgresql', // Path to the directory containing the socket database: 'mydb', // Replace 'mydb' with your database name // additional configurations can be added here if needed });

client.connect(err => { if (err) { console.error('Connection error', err.stack); } else { console.log('Connected successfully'); } });

client.query('SELECT NOW()', (err, res) => { if (err) { console.error('Error executing query', err.stack); } else { console.log('Client query result:', res); } client.end(); // close the client });

ljluestc avatar Dec 23 '23 19:12 ljluestc