Connect to Postgres local vs Vercel Postgres with Kysely

By

Set up Kysely with a local Postgres database using the pg Pool, then switch to Vercel Postgres with the vercel postgres-kysely package.

~~~

I switched a codebase from local Postgres database to Vercel Postgres, which comes with its own optimized package.

For the local database, Kysely sits on top of the standard pg driver. You give it a dialect wrapping a connection pool:

import {
  Kysely,
  PostgresDialect,
} from 'kysely'

import pg from 'pg'

const POSTGRES_URL = process.env.POSTGRES_URL

const dialect = new PostgresDialect({
  pool: new pg.Pool({
    connectionString: POSTGRES_URL,
    max: 10,
  }),
})

export const db = new Kysely({
  dialect
})

The connection string is a normal Postgres URL:

postgresql://user:password@localhost:5432/mydb

Keep it in an environment variable, out of the repository. max: 10 caps how many connections this process can hold, which matters once several instances of the app share one database.

With Vercel Postgres, I used:

import { createKysely } from '@vercel/postgres-kysely'

export const db = createKysely({
  connectionString: process.env.POSTGRES_URL
})

You can even drop the connectionString option entirely: the db instance already knows how to look up the environment variable POSTGRES_URL, which Vercel sets for you when you link the database to the project.

Everything downstream of db stays identical in both setups. That is the point of Kysely’s dialect layer: queries like

const rows = await db
  .selectFrom('notes')
  .select(['id', 'title'])
  .execute()

do not change when the database moves.

To verify which database you are actually talking to, run a quick check at startup:

const result = await sql`select current_database()`.execute(db)
console.log(result.rows)

(sql comes from kysely.) I did this after the switch because the classic failure mode here is an environment variable pointing at the old local database in one environment and at Vercel in another — everything works, just against the wrong data. If the printed database name is not what you expect, fix the environment before debugging anything else.

Tagged: Database · All topics
~~~

Related posts about database: