Kysely: Installing Kysely

You install Kysely in a project using:

npm i kysely

Depending on the kind of database you’ll use (Postgres, MySQL, SQLite), you need to install another library.

In our case we’ll use Postgres, so we also need:

npm i pg

Now in your project create a db.ts (or db.js) file in the src folder, and add:

import { Kysely, PostgresDialect } from 'kysely'

import pg from 'pg'
const { Pool } = pg

const DATABASE_URL = process.env.DATABASE_URL

let dialect

try {
  dialect = new PostgresDialect({
    pool: new Pool({
      connectionString: DATABASE_URL
} catch (e) {

export const db = new Kysely({

We get the DATABASE_URL environment variable using process.env.DATABASE_URL, which is what we do in Hono.

It might differ on other frameworks, for example in Astro we do import.meta.env.DATABASE_URL.

You need to add this to the .env file if you’re working locally (and remember, you never push this “secrets file” to Git - add this to .gitignore).

Something like this, which represents the connection URL to the database (yours will differ depending on the setup):

DATABASE_URL=postgresql://[email protected]/database-name

Now in any file we can import the db object, which is the Kysely instance:

import { db } from './db'

and we can use it to interact with the database, running queries.

We’ll see how in the next lesson.

Lessons in this unit:

0: Introduction
1: ▶︎ Installing Kysely
2: Select queries
3: Inserting data
4: Deleting data
5: Updating data
6: Joins
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!