Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,107 +3,222 @@ title: 'Use Prisma Postgres with Kysely'
sidebar_label: 'Kysely'
metaTitle: 'Quickstart: Kysely with Prisma Postgres (10 min)'
metaDescription: 'Get started with Kysely and Prisma Postgres by creating a type-safe SQL query builder for your database.'
sidebar_custom_props: { badge: '10 min' }
---

[Kysely](https://kysely.dev) is a type-safe TypeScript SQL query builder that provides excellent TypeScript support and a fluent API for building SQL queries. In this guide, you'll learn how to connect Kysely to [Prisma Postgres](/postgres) and start querying your database with full type safety.
[Kysely](https://kysely.dev) is a type-safe TypeScript SQL query builder that provides TypeScript support and a fluent API for building SQL queries. In this guide, you'll learn how to connect Kysely to [Prisma Postgres](/postgres) and start querying your database with full type safety.

## Prerequisites

- **Node.js** - Version 14 or higher
- **TypeScript** - Version 4.6 or higher (5.4+ recommended for better type inference)
- A [Prisma Data Platform](https://console.prisma.io) account
- (Optional) **Kysely setup** - If you already have Kysely configured in your project, skip to [step 2](#2-get-your-direct-connection-string)
- Node.js version 14 or higher
- TypeScript version 4.6 or higher (5.4+ recommended for improved type inference, 5.9+ for better compilation performance)
- Strict mode enabled in your `tsconfig.json` for Kysely's type safety

For detailed Kysely installation and configuration, see the [Kysely Getting started guide](https://kysely.dev/docs/getting-started).
## 1. Create a new project

## 1. Create a Prisma Postgres database
Create a new directory for your project and initialize it with npm:

Follow these steps to create your Prisma Postgres database:
```terminal
mkdir kysely-quickstart
cd kysely-quickstart
npm init -y
```

1. Log in to [Prisma Data Platform](https://console.prisma.io) and open the Console.
2. In a workspace of your choice, click the **New project** button.
3. Type a name for your project in the **Name** field, e.g. `kysely-quickstart`.
4. In the **Prisma Postgres** section, click the **Get started** button.
5. In the **Region** dropdown, select the region that's closest to your current location, e.g. US East (N. Virginia).
6. Click the **Create project** button.
Install TypeScript and initialize it:

At this point, you'll be redirected to the Database page where you will need to wait for a few seconds while the status of your database changes from **PROVISIONING** to **CONNECTED**.
```terminal
npm install --save-dev typescript
npx tsc --init
```

Once the green **CONNECTED** label appears, your database is ready to use!
## 2. Configure TypeScript

Kysely requires TypeScript's strict mode for proper type safety. Update your `tsconfig.json` file:

```json file=tsconfig.json
{
// ...
"compilerOptions": {
// ...
// add-start
"strict": true,
"allowImportingTsExtensions": true,
"noEmit": true
// add-end
// ...
}
// ...
}
```

:::note

## 2. Get your direct connection string
The `strict: true` setting is **required** for Kysely's type safety to work correctly.

To connect to Prisma Postgres via direct TCP, you need to:
:::

1. Open your project in the Prisma Console.
2. Navigate to your active Prisma Postgres instance.
3. Click the **API Keys** tab in the project's sidenav.
4. Click the **Create API key** button.
5. In the popup, provide a **Name** for the API key and click **Create**.
6. Copy the connection string starting with `postgres://`, this is your direct connection string.
In your `package.json`, set the `type` to `module`:

```json
{
// ...
// add-start
"type": "module"
// add-end
// ...
}
```

## 3. Create a new project
## 3. Create a Prisma Postgres database

Create a new directory for your project and initialize it:
You can create a Prisma Postgres database using the `create-db` CLI tool. Follow these steps to create your Prisma Postgres database:

```terminal
mkdir kysely-quickstart
cd kysely-quickstart
npm init -y
npx create-db
```

Then the CLI tool should output:

```terminal
┌ 🚀 Creating a Prisma Postgres database
│ Provisioning a temporary database in us-east-1...
│ It will be automatically deleted in 24 hours, but you can claim it.
◇ Database created successfully!
● Database Connection
│ Connection String:
│ postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require
◆ Claim Your Database
│ Keep your database for free:
│ https://create-db.prisma.io/claim?CLAIM_CODE
│ Database will be deleted on 11/18/2025, 1:55:39 AM if not claimed.
```

Create a `.env` file and add the connection string from the output:

```env file=.env
DATABASE_URL="postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require"
```

:::warning

**Never commit `.env` files to version control.** Add `.env` to your `.gitignore` file to keep credentials secure.

:::

The database created is temporary and will be deleted in 24 hours unless claimed. Claiming moves the database into your [Prisma Data Platform](https://console.prisma.io) account. Visit the claim URL from the output to keep your database.

:::note

To learn more about the `create-db` CLI tool, see the [create-db documentation](/postgres/introduction/npx-create-db).

:::

## 4. Install dependencies

Install Kysely and the PostgreSQL driver:

```terminal
npm install kysely pg dotenv
npm install --save-dev @types/pg tsx
```

## 4. Configure Kysely with Prisma Postgres
**Package breakdown:**
- `kysely`: The type-safe SQL query builder
- `pg`: PostgreSQL driver for Node.js (required by Kysely's PostgresDialect)
- `dotenv`: Loads environment variables from `.env` file
- `@types/pg`: TypeScript type definitions for the pg driver
- `tsx`: TypeScript execution engine for running `.ts` files directly

## 5. Define database types

Create a database connection file that uses your Prisma Postgres connection string:
Create a `src/types.ts` file to define your database schema types:

```typescript file=src/types.ts
import type { Generated } from "kysely";

```typescript file=database.ts
export interface Database {
users: UsersTable;
}

export interface UsersTable {
id: Generated<number>;
email: string;
name: string | null;
}
```

## 6. Configure database connection

Create a `src/database.ts` file to instantiate Kysely with your Prisma Postgres connection:

```typescript file=src/database.ts
import 'dotenv/config'
import type { Database } from './types.ts'
import { Pool } from 'pg'
import { Kysely, PostgresDialect } from 'kysely'

// Parse DATABASE_URL into connection parameters
function parseConnectionString(url: string) {
const parsed = new URL(url)
return {
host: parsed.hostname,
port: parseInt(parsed.port),
user: parsed.username,
password: parsed.password,
database: parsed.pathname.slice(1), // Remove leading '/'
}
}

const connectionParams = parseConnectionString(process.env.DATABASE_URL!)

const dialect = new PostgresDialect({
pool: new Pool({
connectionString: process.env.DATABASE_URL,
...connectionParams,
ssl: true,
max: 10,
})
})

// Define your database interface
interface Database {
users: {
id: number
email: string
name: string | null
}
posts: {
id: number
title: string
content: string | null
published: boolean
author_id: number
}
}

// Database interface is passed to Kysely's constructor, and from now on, Kysely
// knows your database structure.
// Dialect is passed to Kysely's constructor, and from now on, Kysely knows how
// to communicate with your database.
export const db = new Kysely<Database>({
dialect,
})
```

Create a `.env` file and add your Prisma Postgres connection string:

```env file=.env
DATABASE_URL="postgres://USER:PASSWORD@db.prisma.io:5432/?sslmode=require"
```

## 5. Use Kysely with Prisma Postgres
## 7. Run queries

Now you can use Kysely to query your Prisma Postgres database:
Create a `src/script.ts` file:

```typescript file=script.ts
import { db } from './database'
```typescript file=src/script.ts
import { db } from './database.ts'

async function main() {
// Create the users table
await db.schema
.createTable('users')
.ifNotExists()
.addColumn('id', 'serial', (col) => col.primaryKey())
.addColumn('email', 'varchar(255)', (col) => col.notNull().unique())
.addColumn('name', 'varchar(255)')
.execute()

// Insert a user
const user = await db
.insertInto('users')
Expand Down Expand Up @@ -136,16 +251,19 @@ main()
})
```

## Next steps
Run the script:

```terminal
npx tsx src/script.ts
```

Now that you have Kysely connected to Prisma Postgres, you can:
You should receive the following output:

- **Learn more about Kysely** - Check out the [Kysely documentation](https://kysely.dev/docs/intro) for advanced query patterns
- **Explore migrations** - Learn about [Kysely migrations](https://kysely.dev/docs/migrations) for managing schema changes
- **Add more complex queries** - Explore [joins](https://kysely.dev/docs/category/join), [subqueries](https://kysely.dev/docs/examples/join/subquery-join), and [transactions](https://kysely.dev/docs/category/transactions)
```terminal
Created user: { id: 1, email: 'alice@prisma.io', name: 'Alice' }
All users: [ { id: 1, email: 'alice@prisma.io', name: 'Alice' } ]
```

## More info
## Next steps

- [Kysely documentation](https://kysely.dev)
- [Prisma Postgres documentation](/postgres)
- [PostgreSQL driver documentation](https://node-postgres.com)
You've successfully connected Kysely to Prisma Postgres! For more advanced features like schemas, migrations, and complex queries, see the [Kysely documentation](https://kysely.dev/docs/intro).
Loading
Loading