The key here is using RETURNING id in your INSERT query.
The pg wiki has an example that shows how this is done.
// Let's pretend we have a user table with the 'id' as the auto-incrementing primary key
var queryText="INSERT INTO users(password_hash, email) VALUES($1, $2) RETURNING id"
client.query(queryText, ['841l14yah', 'test@te.st'], function(err, result) {
if (err) //handle error
else {
var newlyCreatedUserId = result.rows[0].id;
}
});
or with async/await:
const result = await client.query(queryText, ['841l14yah', 'test@te.st']);
const newlyCreatedUserId = result.rows[0].id;