Serverless & Edge
Minimal Client
Production-ready TypeScript and JavaScript client examples for querying PostgreSQL via fetch().
Minimal fetch() Client
Any runtime with native fetch() support can query PostgreSQL through the gateway. Below is a production-ready, fully typed TypeScript implementation.
TypeScript Client Implementation
// types.ts
export interface GatewayResponse<T = Record<string, unknown>> {
success: boolean;
data?: {
database: string;
command: string;
rowCount: number;
rows: T[];
fields: Array<{
name: string;
dataTypeID: number;
}>;
durationMs: number;
};
error?: {
code: string;
message: string;
pgCode?: string;
cause?: string;
};
}
export interface QueryOptions {
arrayMode?: boolean; // Return positional row arrays instead of objects
lossless?: boolean; // Return exact numeric strings and dates (default: true)
fullResults?: boolean; // Include statement metadata (default: true)
}
// client.ts
export async function queryPostgres<T = Record<string, unknown>>(
sql: string,
parameters: unknown[] = [],
options?: QueryOptions
): Promise<GatewayResponse<T>> {
const gatewayUrl = process.env.PG_GATEWAY_URL;
const apiKey = process.env.PG_GATEWAY_API_KEY;
const database = process.env.PG_GATEWAY_DATABASE;
if (!gatewayUrl || !apiKey || !database) {
throw new Error('Missing required PG_GATEWAY_* environment variables');
}
// Gateway immediate query deadline is 35s.
// Set client timeout to 36s to allow the gateway to return structured errors first.
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 36_000);
try {
const response = await fetch(`${gatewayUrl}/query`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-api-key': apiKey,
'x-database': database,
},
body: JSON.stringify({
query: sql,
parameters,
...(options ? { options } : {}),
}),
signal: controller.signal,
});
const payload = (await response.json()) as GatewayResponse<T>;
if (!response.ok || !payload.success) {
const errorCode = payload.error?.code ?? `HTTP_${response.status}`;
const errorMessage = payload.error?.message ?? 'Unknown database gateway error';
const error = new Error(`[${errorCode}] ${errorMessage}`);
(error as any).code = errorCode;
(error as any).pgCode = payload.error?.pgCode;
throw error;
}
return payload;
} finally {
clearTimeout(timeoutId);
}
}Usage Examples
1. Basic Parameterized Query
interface User {
id: number;
email: string;
created_at: string;
}
const result = await queryPostgres<User>(
'SELECT id, email, created_at FROM public.users WHERE status = $1 ORDER BY id DESC LIMIT $2',
['active', 10]
);
console.log(`Retrieved ${result.data?.rowCount} users:`);
for (const user of result.data?.rows ?? []) {
console.log(`- ${user.email} (ID: ${user.id})`);
}2. Positional Rows (arrayMode)
For queries where performance or duplicate column names matter, pass options.arrayMode: true:
const result = await queryPostgres(
'SELECT u.id, u.name, o.id, o.amount FROM users u JOIN orders o ON u.id = o.user_id WHERE u.id = $1',
[42],
{ arrayMode: true }
);
// result.data.rows contains arrays of values:
// [[42, "Alice", 101, "99.95"], [42, "Alice", 102, "14.50"]]
console.log(result.data?.rows);3. Inserting Data with RETURNING
const result = await queryPostgres(
'INSERT INTO public.events (type, payload) VALUES ($1, $2) RETURNING id, created_at',
['user_signup', JSON.stringify({ plan: 'pro', referrer: 'twitter' })]
);
const newEventId = result.data?.rows[0]?.id;
console.log(`Created event with ID: ${newEventId}`);Best Practices for Secrets
- Use Platform Secret Stores: In Cloudflare Workers, use
wrangler secret put PG_GATEWAY_API_KEY. In Vercel, use encrypted Environment Variables. - Never Expose to Client-Side Browsers: The
x-api-keyis a bearer token with direct database execution permissions. Only make gateway requests from backend/serverless code. - Use Granular Scopes: Create separate API keys per function with table-specific CRUD rights. A microservice that only reads metrics should not hold a key with
c,u, ordrights.
