Use Pool and Client for sessions and transactions
mainWhen you require session support, interactive transactions, or compatibility with query builders like Kysely or Zapatos, use the Pool or Client constructors instead of the neon() function. These use WebSockets for communication.
Critical Usage Rules for Serverless/Edge
In environments like Vercel Edge Functions or Cloudflare Workers, WebSocket connections cannot outlive a single request.
- Scope: You must create, use, and close
PoolorClientobjects within a single request handler. - Avoid Global Scope: Do not create these objects outside the request handler.
- Cleanup: Always close the connection (e.g., using
pool.end()orclient.end()) to avoid exhausting available connections. In Vercel Edge Functions, usectx.waitUntil(pool.end())to ensure the connection closes without delaying the response.
Node.js WebSocket Configuration
In Node.js v21 and earlier, you must manually provide a WebSocket constructor (e.g., from the ws package) via neonConfig.webSocketConstructor.
import { Pool, neonConfig } from '@neondatabase/serverless';
import ws from 'ws';
// Required for Node v21 and below
neonConfig.webSocketConstructor = ws;
const pool = new Pool({ connectionString: process.env.DATABASE_URL });