node-postgres for serverless environments from neon.com
The @neondatabase/serverless package is a PostgreSQL driver engineered specifically for serverless and edge computing environments where traditional TCP connections aren't available. It replaces node-postgres's network primitives with WebSocket-based implementations, enabling database queries on platforms like Cloudflare Workers, Vercel Edge Functions, and AWS Lambda without cold-start connection penalties.
The driver maintains full API compatibility with the widely-used node-postgres (pg) library, meaning existing code can be migrated by simply swapping the import statement. It exports the same Pool and Client interfaces, supports parameterized queries, and includes native TypeScript definitions. This compatibility extends to popular ORMs like Prisma and Drizzle, which have built adapters specifically for this driver.
With over 1 million weekly downloads, this package has become the de facto standard for PostgreSQL access in edge environments. It's maintained by Neon, a serverless Postgres provider, but works with any PostgreSQL database that's network-accessible. The driver handles connection lifecycle, message pipelining, and WebSocket negotiation automatically, abstracting away the complexity of non-TCP database communication.
The package offers multiple query interfaces: the traditional callback/promise-based Pool API for compatibility, and a modern template literal syntax through the neon() function for more ergonomic query writing. Both approaches support prepared statements and connection pooling, essential for production serverless workloads.
import { Pool } from '@neondatabase/serverless';
// Using Pool for connection management
const pool = new Pool({
connectionString: process.env.DATABASE_URL
});
export async function getUserWithPosts(userId: number) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const userResult = await client.query(
'SELECT id, email, name FROM users WHERE id = $1',
[userId]
);
if (userResult.rows.length === 0) {
throw new Error('User not found');
}
const postsResult = await client.query(
'SELECT id, title, created_at FROM posts WHERE user_id = $1 ORDER BY created_at DESC LIMIT 10',
[userId]
);
await client.query('COMMIT');
return {
user: userResult.rows[0],
posts: postsResult.rows
};
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
// Alternative: Using template literal syntax
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL);
export async function createPost(userId: number, title: string, content: string) {
const result = await sql`
INSERT INTO posts (user_id, title, content, created_at)
VALUES (${userId}, ${title}, ${content}, NOW())
RETURNING id, title, created_at
`;
return result[0];
}Edge API Routes: Building API endpoints on Vercel Edge Runtime or Cloudflare Workers that need to query PostgreSQL without the overhead of traditional database connections. The WebSocket-based approach eliminates TCP handshake delays that plague serverless functions.
Next.js Server Components: Fetching data directly in React Server Components deployed to edge networks. The driver's low-latency design enables fast database queries closer to end users geographically.
Serverless Background Jobs: Running cron jobs or event-driven workers on platforms like AWS Lambda that process database records. The driver handles connection cleanup automatically, preventing connection leaks common in serverless.
Multi-tenant SaaS Applications: Building applications where each request might query different tenant databases. The lightweight connection model makes it feasible to establish connections per-request without connection pool exhaustion.
Hybrid Architectures: Migrating existing node-postgres codebases to edge environments incrementally. The API compatibility means you can use the same queries and business logic across traditional Node.js servers and edge functions.
npm install @neondatabase/serverlesspnpm add @neondatabase/serverlessbun add @neondatabase/serverless