apps/docs/content/docs.v6/(index)/prisma-postgres/quickstart/kysely.mdx
Kysely 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 and start querying your database with full type safety.
tsconfig.json for Kysely's type safetyCreate a new directory for your project and initialize it with npm:
mkdir kysely-quickstart
cd kysely-quickstart
npm init -y
Install TypeScript and initialize it:
npm install --save-dev typescript
npx tsc --init
Kysely requires TypeScript's strict mode for proper type safety. Update your tsconfig.json file:
{
// ...
"compilerOptions": {
// ...
"strict": true, // [!code ++]
"allowImportingTsExtensions": true, // [!code ++]
"noEmit": true // [!code ++]
// ...
}
// ...
}
:::note
The strict: true setting is required for Kysely's type safety to work correctly.
:::
In your package.json, set the type to module:
{
// ...
"type": "module" // [!code ++]
// ...
}
You can create a Prisma Postgres database using the create-db CLI tool. Follow these steps to create your Prisma Postgres database:
npx create-db
Then the CLI tool should output:
┌ 🚀 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:[email protected]: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:
DATABASE_URL="postgresql://hostname:[email protected]: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 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.
:::
Install Kysely and the PostgreSQL driver:
npm install kysely pg dotenv
npm install --save-dev @types/pg tsx
Package breakdown:
kysely: The type-safe SQL query builderpg: 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 drivertsx: TypeScript execution engine for running .ts files directlyCreate a src/types.ts file to define your database schema types:
import type { Generated } from "kysely";
export interface Database {
users: UsersTable;
}
export interface UsersTable {
id: Generated<number>;
email: string;
name: string | null;
}
Create a src/database.ts file to instantiate Kysely with your Prisma Postgres connection:
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({
...connectionParams,
ssl: true,
max: 10,
}),
});
// 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 src/script.ts file:
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")
.values({
email: "[email protected]",
name: "Alice",
})
.returningAll()
.executeTakeFirstOrThrow();
console.log("Created user:", user);
// Query all users
const users = await db.selectFrom("users").selectAll().execute();
console.log("All users:", users);
}
main()
.then(async () => {
await db.destroy();
})
.catch(async (error) => {
console.error("Error:", error);
await db.destroy();
process.exit(1);
});
Run the script:
npx tsx src/script.ts
You should receive the following output:
Created user: { id: 1, email: '[email protected]', name: 'Alice' }
All users: [ { id: 1, email: '[email protected]', name: 'Alice' } ]
You've successfully connected Kysely to Prisma Postgres! For more advanced features like schemas, migrations, and complex queries, see the Kysely documentation.