A small utility for executing PostgreSQL queries within a session context using pg. It allows you to temporarily set PostgreSQL session variables (set_config) for RLS (Row-Level Security) and other scoped operations.
npm install pg-query-context- Sets session-level context (e.g., role, user ID) using
set_config. - Automatically wraps execution in a transaction (
BEGIN/COMMIT). - Automatically rolls back on error.
- Supports both
PoolandClientfrompg.
import pgQueryContext from 'pg-query-context';
import { Pool } from 'pg';
const pool = new Pool();
const result = await pgQueryContext({
client: pool,
context: {
'role': 'authenticated',
'myapp.user_id': '123e4567-e89b-12d3-a456-426614174000'
},
query: 'SELECT * FROM app_private.do_something_secure($1)',
variables: ['input-value']
});
console.log(result.rows);| Name | Type | Required | Description |
|---|---|---|---|
client |
Pool or ClientBase |
✅ | The PostgreSQL client or pool to use |
context |
Record<string, string> |
❌ | Key-value session variables to be set via set_config |
query |
string |
✅ | SQL query to run |
variables |
any[] |
❌ | Parameterized query variables |
For multi-query RLS transactions, use withPgClient which gives you a connected client within a scoped transaction:
import { withPgClient } from 'pg-query-context';
import { Pool } from 'pg';
const pool = new Pool();
const user = await withPgClient(
pool,
{ 'role': 'authenticated', 'jwt.claims.user_id': userId },
async (client) => {
const { rows: [row] } = await client.query('SELECT * FROM app_public.current_user()');
await client.query('UPDATE app_public.users SET last_seen = now() WHERE id = $1', [row.id]);
return row;
}
);| Name | Type | Required | Description |
|---|---|---|---|
pool |
Pool |
✅ | The PostgreSQL pool to acquire a client from |
context |
Record<string, string> |
✅ | Session variables set via set_config |
fn |
(client: PoolClient) => T |
✅ | Callback receiving the connected client |
opts |
{ skipTransaction?: boolean } |
❌ | Skip BEGIN/COMMIT wrapping (e.g., inside existing txn) |
app.post('/secure-endpoint', async (req, res) => {
const authToken = req.headers.authorization;
const result = await pgQueryContext({
client: pool,
context: {
'role': 'authenticated',
'myapp.token': authToken,
},
query: 'SELECT * FROM app_private.verify_token($1)',
variables: [authToken],
});
if (!result.rows.length) {
return res.status(401).json({ error: 'Unauthorized' });
}
res.json({ user: result.rows[0] });
});