What you will learn:
How to connect from Kysely using different drivers
How to define TypeScript schemas for Kysely
How to run migrations and queries
Related resources
Kysely is a type-safe SQL query builder for TypeScript. Instead of mapping objects to tables like an ORM, it gives you an API for building SQL queries and uses TypeScript's type system for type checking and autocompletion. This guide walks you through connecting your application to a Lakebase Postgres database using Kysely.
To connect a TypeScript/Node.js project to Neon using Kysely, follow these steps:
Create a TypeScript/Node.js project
Create a new directory for your project and navigate into it:
mkdir my-kysely-neon-project cd my-kysely-neon-projectInitialize a new Node.js project:
npm init -yInstall TypeScript and initialize a configuration file (Kysely requires TypeScript 4.6+):
npm install -D typescript tsx @types/node npx tsc --initConfigure your
tsconfig.jsonfor type safety and module resolution. Ensure you have at least the following settings:{ "compilerOptions": { // ... other settings ... "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "types": ["node"], "strict": true, "allowImportingTsExtensions": true, "noEmit": true } }Recent versions of
tsc --initset"types": [], which hides the Node.js types installed by@types/node. Set"types": ["node"]so names likeprocesstype-check.Configure your
package.jsonto use ES modules.npm init -ywrites"type": "commonjs", so change it to:{ // ... other settings ... "type": "module" }Create a Neon project
If you do not have one already, create a Neon project.
- Navigate to the Projects page in the Neon Console.
- Click New Project.
- Specify your project settings and click Create Project.
Get your connection string
Find your database connection string by clicking the Connect button in the Console nav to open the Connect to your branch modal. Select a branch, a user, and the database you want to connect to. A connection string is constructed for you.

Create a
.envfile in your project's root directory and add the connection string to it. Your.envfile should look like this:DATABASE_URL="postgresql://[user]:[password]@[neon_hostname]/[dbname]?sslmode=require&channel_binding=require"If you use
node-postgres,pg8.23 and later print aSECURITY WARNINGforsslmode=require. Change it tosslmode=verify-fullto keep the same behavior without the warning.Install Kysely and a driver
Install the Kysely core package and the necessary driver dependencies. Choose one of the following drivers based on your application's needs. For a Node.js script or long-running server, use
node-postgres.Use the Neon serverless HTTP driver for serverless/edge environments (for example, Vercel Edge, Cloudflare Workers). This requires the
kysely-neondialect.Note
The Neon serverless driver over HTTP is stateless and does not support persistent connections or interactive transactions. If your application requires transactions, we recommend using the Neon WebSocket driver or
node-postgres.npm install kysely kysely-neon @neondatabase/serverless dotenvCreate a table (optional)
You can skip this step if you already have tables in your database.
Unlike many ORMs, Kysely does not automatically sync your TypeScript types with the database schema. Tables must exist before you query them.
To create the table with Kysely's migration helpers (
upanddown) instead, skip this step and follow Run a migration below. Don't do both: the migration fails if theuserstable already exists.Navigate to the SQL Editor in the Neon Console and run the following SQL command to create a
userstable:CREATE TABLE users ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT NOW() NOT NULL );Define the database schema
Kysely is TypeScript-first and requires you to define an interface that describes your database structure. This interface tells Kysely which tables and columns exist.
Create a file
src/types.ts:import type { Generated, Selectable, Insertable, Updateable } from 'kysely'; export interface Database { users: UsersTable; } export interface UsersTable { // Columns that are generated by the database should be marked // using the `Generated` type. id: Generated<number>; name: string; email: string; created_at: Generated<Date>; } // You can use these types in your application code export type User = Selectable<UsersTable>; export type NewUser = Insertable<UsersTable>; export type UserUpdate = Updateable<UsersTable>;Initialize the Kysely client
Create a file
src/db.tsto initialize and export your Kysely instance. The configuration depends on the driver you selected.When using the HTTP driver, use
NeonDialectfromkysely-neon.import 'dotenv/config'; import { Kysely } from 'kysely'; import { NeonDialect } from 'kysely-neon'; import { neon } from '@neondatabase/serverless'; import type { Database } from './types.ts'; export const db = new Kysely<Database>({ dialect: new NeonDialect({ neon: neon(process.env.DATABASE_URL!), }), });Run a migration (optional)
You can skip this step if you do not intend to use Kysely for migrations.
Kysely manages migrations using TypeScript files. Create a migration to create the
userstable using Kysely's schema builder.-
Create a folder named
migrationsin your project's root directory:mkdir migrations -
Create a file
migrations/001_create_users.ts:import { Kysely, sql } from 'kysely'; export async function up(db: Kysely<any>): Promise<void> { await db.schema .createTable('users') .addColumn('id', 'serial', (col) => col.primaryKey()) .addColumn('name', 'text', (col) => col.notNull()) .addColumn('email', 'text', (col) => col.unique().notNull()) .addColumn('created_at', 'timestamp', (col) => col.defaultTo(sql`now()`).notNull()) .execute(); } export async function down(db: Kysely<any>): Promise<void> { await db.schema.dropTable('users').execute(); } -
Create a script to run the migration,
src/migrate.ts. In Kysely 0.29 and later,MigratorandFileMigrationProviderare imported fromkysely/migration.import * as path from 'path'; import { promises as fs } from 'fs'; import { fileURLToPath } from 'url'; import { Migrator, FileMigrationProvider } from 'kysely/migration'; import { db } from './db.ts'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); async function migrateToLatest() { const migrator = new Migrator({ db, provider: new FileMigrationProvider({ fs, path, migrationFolder: path.join(__dirname, '../migrations'), }), }); const { error, results } = await migrator.migrateToLatest(); results?.forEach((it) => { if (it.status === 'Success') { console.log(`migration "${it.migrationName}" was executed successfully`); } else if (it.status === 'Error') { console.error(`failed to execute migration "${it.migrationName}"`); } }); if (error) { console.error('failed to migrate'); console.error(error); process.exit(1); } await db.destroy(); } migrateToLatest(); -
Run the migration:
npx tsx src/migrate.ts
-
Query the database
Create a file
src/index.tsto interact with your database. The following example demonstrates how to perform standard CRUD operations (Create, Read, Update, Delete) using Kysely.import { db } from './db.ts'; async function main() { try { // 1. Insert (Create) const { id } = await db .insertInto('users') .values({ name: 'Neon User', email: `user-${Date.now()}@example.com`, }) .returning('id') .executeTakeFirstOrThrow(); console.log(`User created with ID: ${id}`); // 2. Select (Read) const users = await db.selectFrom('users').selectAll().execute(); console.log('All users:', users); // 3. Update const updateResult = await db .updateTable('users') .set({ name: 'Updated Neon User' }) .where('id', '=', id) .executeTakeFirst(); console.log(`User updated. Rows affected: ${updateResult.numUpdatedRows}`); // 4. Delete const deleteResult = await db.deleteFrom('users').where('id', '=', id).executeTakeFirst(); console.log(`User deleted. Rows affected: ${deleteResult.numDeletedRows}`); } catch (error) { console.error('Error querying the database:', error); } finally { // Close the connection await db.destroy(); } } main();Run the script using
tsx:npx tsx src/index.tsYou should see output indicating that the user was created and then fetched from the database.
$ npx tsx src/index.ts User created with ID: 1 All users: [ { id: 1, name: 'Neon User', email: 'user-1794150348648@example.com', created_at: 2026-11-08T15:05:48.648Z } ] User updated. Rows affected: 1 User deleted. Rows affected: 1For more advanced use cases, such as complex filters, joins, transactions, and subqueries, see the Kysely documentation.
Learn more
Next steps
- Set up Managed Better Auth: Add managed authentication that branches with your database
- Add Object Storage: S3-compatible file storage that branches with your database
- Deploy a Function: Run backend compute next to your database, no separate hosting needed
- Call an LLM with AI Gateway: Access foundation models from Anthropic, OpenAI, Google, and more with one credential
- Realtime: Build fully-reactive realtime Kysely apps on Neon using your existing schema and queries »








