node-postgres, Connection terminated unexpectedly

John Jeromin picture John Jeromin · Apr 6, 2018 · Viewed 13.5k times · Source

I'm trying to connect to a remote database using node-postgres.

I can connect using the psql client, but I get the error Connection terminated unexpectedly while trying to run this (with same connection string as in psql client):

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

const pool = new Pool({
  connectionString: connectionString,
})

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

const client = new Client({
  connectionString: connectionString,
})
client.connect()

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

I've also been trying to connect with Sequelize ORM, but got the same error.

@EDIT

Using native mode fixed problem for client query using pg, and sequelize

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

Answer

Arturo Torres Vázquez picture Arturo Torres Vázquez · Mar 12, 2019

I started having the same problem, but only with long time queries, i found a possible solution by setting idleTimeoutMillis in the Pool constructor, for example to 20000 (the default value is 10000)

See https://node-postgres.com/api/pool#new-pool-config-object-