What is @neondatabase/serverless?
@neondatabase/serverless is an npm package designed to facilitate serverless interactions with Neon, a serverless PostgreSQL database. It provides a set of tools and utilities to connect, query, and manage PostgreSQL databases in a serverless environment, making it easier to build scalable and efficient applications.
What are @neondatabase/serverless's main functionalities?
Connecting to a Neon Database
This feature allows you to establish a connection to a Neon database using the provided connection string. The code sample demonstrates how to create a new client instance and connect to the database.
const { Client } = require('@neondatabase/serverless');
const client = new Client({
connectionString: process.env.NEON_DATABASE_URL,
});
async function connect() {
await client.connect();
console.log('Connected to Neon Database');
}
connect();
Executing SQL Queries
This feature allows you to execute SQL queries against the connected Neon database. The code sample demonstrates how to connect to the database, execute a SELECT query, and log the results.
const { Client } = require('@neondatabase/serverless');
const client = new Client({
connectionString: process.env.NEON_DATABASE_URL,
});
async function executeQuery() {
await client.connect();
const res = await client.query('SELECT * FROM users');
console.log(res.rows);
await client.end();
}
executeQuery();
Handling Transactions
This feature allows you to handle transactions in the Neon database. The code sample demonstrates how to begin a transaction, execute an insert query, commit the transaction, and handle errors by rolling back the transaction if necessary.
const { Client } = require('@neondatabase/serverless');
const client = new Client({
connectionString: process.env.NEON_DATABASE_URL,
});
async function handleTransaction() {
await client.connect();
try {
await client.query('BEGIN');
await client.query('INSERT INTO users(name) VALUES($1)', ['John Doe']);
await client.query('COMMIT');
console.log('Transaction committed');
} catch (e) {
await client.query('ROLLBACK');
console.error('Transaction rolled back', e);
} finally {
await client.end();
}
}
handleTransaction();
Other packages similar to @neondatabase/serverless
pg
The 'pg' package is a popular PostgreSQL client for Node.js. It provides a comprehensive set of features for connecting to and interacting with PostgreSQL databases. Compared to @neondatabase/serverless, 'pg' is more general-purpose and widely used, but it may require additional configuration for serverless environments.
knex
The 'knex' package is a SQL query builder for Node.js, supporting multiple database types including PostgreSQL. It provides a flexible and powerful API for building and executing SQL queries. While 'knex' offers more advanced query building capabilities, it is not specifically tailored for serverless environments like @neondatabase/serverless.
sequelize
The 'sequelize' package is a promise-based Node.js ORM for various SQL databases, including PostgreSQL. It provides a higher-level abstraction for database interactions, including model definitions and associations. Compared to @neondatabase/serverless, 'sequelize' offers more features for complex data modeling but may introduce additional overhead for simple use cases.
@neondatabase/serverless [BETA]
This package from Neon shims the node-postgres pg
library to work on edge runtimes such as Cloudflare Workers — places where TCP sockets are not available — via a WebSocket proxy.
Note: this package also works in web browsers, but in most cases it's not appropriate to publicly deploy that way, since it would reveal your Postgres credentials.
How to use it
Where you'd otherwise install pg
and @types/pg
, instead run npm install @neondatabase/serverless
.
Then use it the same way you'd use pg
. For example, make your Neon database connection string available in env.DATABASE_URL
, then:
import { Client } from '@neondatabase/serverless';
async function whatsTheTimeMrPostgres() {
const client = new Client(env.DATABASE_URL);
await client.connect();
const { rows: [{ now }] } = await client.query('select now();');
await client.end();
return now;
}
Run your own WebSocket proxy
The package comes configured to connect to Neon's WebSocket proxy, which will then allow onward connections only to Neon databases.
But you can run your own copy of the WebSocket proxy, and configure it to allow onward connections to your own Postgres instances.
First, you'll need to set up the proxy itself somewhere public-facing (or on localhost
for development). See https://github.com/neondatabase/wsproxy for the Go code and instructions.
Then you'll need to set two options on this package — wsProxy
and rootCerts
— by importing the neonConfig
object. For example:
import { Client, neonConfig } from '@neondatabase/serverless';
neonConfig.wsProxy = 'my-wsproxy.example.com';
neonConfig.rootCerts = `
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
...
-----END CERTIFICATE-----
`;
async function whatsTheTimeMrPostgres() {
const client = new Client(env.DATABASE_URL);
await client.connect();
const { rows: [{ now }] } = await client.query('select now();');
await client.end();
return now;
}
wsProxy
The wsProxy
setting should point to the WebSocket proxy you just set up. Usually that will just be a URL host string, but if you want to run different proxies depending on the database host (e.g. to match regions) you can also pass a function with the signature (dbHost: string) => string
. For example:
neonConfig.wsProxy = (dbHost) =>
/[.]eu[.]db[.]example[.]com$/.test(dbHost) ?
'my-wsproxy.eu.example.com' :
'my-wsproxy.us.example.com';
rootCerts
We bundle our own TLS implementation, which needs to know what root (certificate authority) certificates to trust. The default value of rootCerts
is the ISRG Root X1 certificate, which is appropriate for servers secured with Let’s Encrypt certificates.
If you're using any other certificate authority to secure Postgres connections, provide the root certificate(s) in PEM format to the rootCerts
option.
TLS version
Please note that the library requires your Postgres installation to support TLS 1.3.
Orientation
The code is at https://github.com/neondatabase/serverless. Most of it is in shims/net/index.ts
. Alongside that file, tls.js
and tls.wasm
come from https://github.com/jawj/cloudflare-pg-client
(where we patch deno-postgres
for a similar purpose, and compile WolfSSL with emscripten along the way).
-
To update the npm package, run ./export.sh
, then cd dist/npm
and npm publish
.
-
To run or deploy the test app on Cloudflare, create a .dev.vars
file containing DATABASE_URL=postgres://connection_string
, run npx wrangler dev --local
or npx wrangler publish
.
-
To run the test app in a browser, create a .dev.vars
file, run ./build.sh
, start a local server at the repo root, and visit http://localhost:8080/dist/deploy/
(replacing the port number as appropriate).