Gathering detailed insights and metrics for @neondatabase/serverless
Gathering detailed insights and metrics for @neondatabase/serverless
Gathering detailed insights and metrics for @neondatabase/serverless
Gathering detailed insights and metrics for @neondatabase/serverless
Connect to Neon PostgreSQL from serverless/worker/edge functions
npm install @neondatabase/serverless
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
364 Stars
312 Commits
16 Forks
6 Watching
34 Branches
32 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
TypeScript (95.14%)
Shell (3.89%)
JavaScript (0.97%)
Cumulative downloads
Total Downloads
Last day
28.5%
45,507
Compared to previous day
Last week
10.2%
227,277
Compared to previous week
Last month
14.6%
893,467
Compared to previous month
Last year
715%
6,911,430
Compared to previous year
1
@neondatabase/serverless
is Neon's PostgreSQL driver for JavaScript and TypeScript. It's:
pg
(on which it's based)Install it with your preferred JavaScript package manager. It's named @neondatabase/serverless
on npm and @neon/serverless
on JSR. So, for example:
1npm install @neondatabase/serverless
or
1bunx jsr add @neon/serverless
Using TypeScript? No worries: types are included either way.
Get your connection string from the Neon console and set it as an environment variable. Something like:
DATABASE_URL=postgres://username:password@host.neon.tech/neondb
For one-shot queries, use the neon
function. For instance:
1import { neon } from '@neondatabase/serverless'; 2const sql = neon(process.env.DATABASE_URL); 3 4const [post] = await sql`SELECT * FROM posts WHERE id = ${postId}`; 5// `post` is now { id: 12, title: 'My post', ... } (or undefined)
Note: interpolating ${postId}
here is safe from SQL injection.
Turn this example into a complete API endpoint deployed on Vercel Edge Functions at https://myapp.vercel.dev/api/post?postId=123
by following two simple steps:
api/post.ts
:1import { neon } from '@neondatabase/serverless'; 2const sql = neon(process.env.DATABASE_URL); 3 4export default async (req: Request, ctx: any) => { 5 // get and validate the `postId` query parameter 6 const postId = parseInt(new URL(req.url).searchParams.get('postId'), 10); 7 if (isNaN(postId)) return new Response('Bad request', { status: 400 }); 8 9 // query and validate the post 10 const [post] = await sql`SELECT * FROM posts WHERE id = ${postId}`; 11 if (!post) return new Response('Not found', { status: 404 }); 12 13 // return the post as JSON 14 return new Response(JSON.stringify(post), { 15 headers: { 'content-type': 'application/json' } 16 }); 17} 18 19export const config = { 20 runtime: 'edge', 21 regions: ['iad1'], // specify the region nearest your Neon DB 22};
1npm install -g vercel # install vercel CLI 2npx vercel env add DATABASE_URL # paste Neon connection string, select all environments 3npx vercel dev # check working locally, then ... 4npx vercel deploy
The neon
query function has a few additional options.
A query using the neon
function, as shown above, is carried by an https fetch request.
This should work — and work fast — from any modern JavaScript environment. But you can only send one query at a time this way: sessions and transactions are not supported.
transaction()
Multiple queries can be issued via fetch request within a single, non-interactive transaction by using the transaction()
function. This is exposed as a property on the query function.
For example:
1import { neon } from '@neondatabase/serverless'; 2const sql = neon(process.env.DATABASE_URL); 3const showLatestN = 10; 4 5const [posts, tags] = await sql.transaction([ 6 sql`SELECT * FROM posts ORDER BY posted_at DESC LIMIT ${showLatestN}`, 7 sql`SELECT * FROM tags`, 8]);
There are some additional options when using transaction()
.
Pool
and Client
Use the Pool
or Client
constructors, instead of the functions described above, when you need:
session or interactive transaction support, and/or
compatibility with node-postgres, which supports query libraries like Kysely or Zapatos.
Queries using Pool
and Client
are carried by WebSockets. There are two key things to know about this:
In Node.js and some other environments, there's no built-in WebSocket support. In these cases, supply a WebSocket constructor function.
In serverless environments such as Vercel Edge Functions or Cloudflare Workers, WebSocket connections can't outlive a single request.
That means Pool
or Client
objects must be connected, used and closed within a single request handler. Don't create them outside a request handler; don't create them in one handler and try to reuse them in another; and to avoid exhausting available connections, don't forget to close them.
These points are demonstrated in the examples below.
The full API guide to Pool
and Client
can be found in the node-postgres docs.
There are a few additional configuration options that apply to Pool
and Client
here.
Pool.connect()
In Node.js, it takes two lines to configure WebSocket support. For example:
1import { Pool, neonConfig } from '@neondatabase/serverless'; 2 3import ws from 'ws'; 4neonConfig.webSocketConstructor = ws; // <-- this is the key bit 5 6const pool = new Pool({ connectionString: process.env.DATABASE_URL }); 7pool.on('error', (err) => console.error(err)); // deal with e.g. re-connect 8// ... 9 10const client = await pool.connect(); 11 12try { 13 await client.query('BEGIN'); 14 const { 15 rows: [{ id: postId }], 16 } = await client.query('INSERT INTO posts (title) VALUES ($1) RETURNING id', [ 17 'Welcome', 18 ]); 19 await client.query('INSERT INTO photos (post_id, url) VALUES ($1, $2)', [ 20 postId, 21 's3.bucket/photo/url', 22 ]); 23 await client.query('COMMIT'); 24} catch (err) { 25 await client.query('ROLLBACK'); 26 throw err; 27} finally { 28 client.release(); 29} 30 31// ... 32await pool.end();
Other WebSocket libraries are available. For example, you could replace ws
in the above example with undici
:
1import { WebSocket } from 'undici'; 2neonConfig.webSocketConstructor = WebSocket;
Pool.query()
We can rewrite the Vercel Edge Function shown above (under the heading 'Deploy it') to use Pool
, as follows:
1import { Pool } from '@neondatabase/serverless'; 2 3// *don't* create a `Pool` or `Client` here, outside the request handler 4 5export default async (req: Request, ctx: any) => { 6 // create a `Pool` inside the request handler 7 const pool = new Pool({ connectionString: process.env.DATABASE_URL }); 8 9 // get and validate the `postId` query parameter 10 const postId = parseInt(new URL(req.url).searchParams.get('postId'), 10); 11 if (isNaN(postId)) return new Response('Bad request', { status: 400 }); 12 13 // query and validate the post 14 const [post] = await pool.query('SELECT * FROM posts WHERE id = $1', [postId]); 15 if (!post) return new Response('Not found', { status: 404 }); 16 17 // end the `Pool` inside the same request handler 18 // (unlike `await`, `ctx.waitUntil` won't hold up the response) 19 ctx.waitUntil(pool.end()); 20 21 // return the post as JSON 22 return new Response(JSON.stringify(post), { 23 headers: { 'content-type': 'application/json' } 24 }); 25} 26 27export const config = { 28 runtime: 'edge', 29 regions: ['iad1'], // specify the region nearest your Neon DB 30};
Note: we don't actually use the pooling capabilities of Pool
in this example. But it's slightly briefer than using Client
and, because Pool.query
is designed for one-shot queries, we may in future automatically route these queries over https for lower latency.
Client
Using Client
instead, the example looks like this:
1import { Client } from '@neondatabase/serverless'; 2 3// don't create a `Pool` or `Client` here, outside the request handler 4 5export default async (req: Request, ctx: any) => { 6 // create a `Client` inside the request handler 7 const client = new Client(process.env.DATABASE_URL); 8 await client.connect(); 9 10 // get and validate the `postId` query parameter 11 const postId = parseInt(new URL(req.url).searchParams.get('postId'), 10); 12 if (isNaN(postId)) return new Response('Bad request', { status: 400 }); 13 14 // query and validate the post 15 const [post] = await client.query('SELECT * FROM posts WHERE id = $1', [postId]); 16 if (!post) return new Response('Not found', { status: 404 }); 17 18 // end the `Client` inside the same request handler 19 // (unlike `await`, `ctx.waitUntil` won't hold up the response) 20 ctx.waitUntil(client.end()); 21 22 // return the post as JSON 23 return new Response(JSON.stringify(post), { 24 headers: { 'content-type': 'application/json' } 25 }); 26} 27 28export const config = { 29 runtime: 'edge', 30 regions: ['iad1'], // specify the region nearest your Neon DB 31};
These repos show how to use @neondatabase/serverless
with a variety of environments and tools:
This package comes configured to connect to a Neon database. But you can also use it to connect to your own Postgres instances if you run your own WebSocket proxy.
This code is released under the MIT license.
Please visit Neon Community or Support.
No vulnerabilities found.
No security vulnerabilities found.