Skip to main content
PlanetScale supports connections via the Neon serverless driver. This is a good option for connecting to your PlanetScale database in serverless environments like Vercel Functions or AWS Lambda. You can find detailed documentation on Neon’s website or on the GitHub repository.

Limitations

The Neon serverless driver supports two modes: HTTP and WebSockets. PlanetScale only supports WebSocket connections, so you must use a Pool object to execute queries, as shown in the example below. You also must disable pileline connections. More info in the security section below.

Using the driver

1

First, install the driver via npm:
npm install @neondatabase/serverless
2

You’ll need to create a Postgres role to use with the driver. Once you have these credentials, place them in environment variables:
DATABASE_HOST=XXXX.pg.psdb.cloud
DATABASE_PORT=6432
DATABASE_NAME=XXXX
DATABASE_USERNAME=XXXX
DATABASE_PASSWORD=pscale_pw_XXXX
These can all be added to a unified Postgres connection URL for use by the driver:
DATABASE_URL="postgresql://$DATABASE_USERNAME:$DATABASE_PASSWORD@$DATABASE_HOST:$DATABASE_PORT/$DATABASE_NAME"
3

When connecting in your worker function, you must set the following configuration option when using the driver.
neonConfig.pipelineConnect = false;
4

With this in place, pass the process.env.DATABASE_URL to the serverless driver Pool object, and begin executing queries on your PlanetScale database. Here’s a complete example using the connection string created above:
import ws from "ws";
import { Pool, neonConfig } from "@neondatabase/serverless";

neonConfig.webSocketConstructor = ws;
// This MUST be set for PlanetScale Postgres connections
neonConfig.pipelineConnect = false;

const pool = new Pool({
    connectionString: process.env.DATABASE_URL,
});

const { rows } = await pool.query('SELECT * FROM users;', []);
console.log(rows);

await pool.end();

Security

PlanetScale requires SCRAM-SHA-256 for all authentication to Postgres servers. We maintain this strict requirement for security purposes. Because of this, you must set neonConfig.pipelineConnect = false; when using the Neon serverless driver. This adds a bit of additional latency, but is necessary to connect using SCRAM-SHA-256. When this is "password" (the default value) it requires using cleartext password authentication, reducing connection security.