Connecting database to Next Js using KYSELY

Sivaganesh Panditi
1 min readMay 6, 2024

--

We can connect database to Next Js application in many ways. In this article, I will show how to connect POSTGRES database using KYSELY (ORM) QUERY BUILDER

# Install sequelize using npm
npm install kysely pg @types/pg

Set up database connection in .env file as shown below

DB_HOST=<!--replace with your database hostname -->
DB_USER=<!--replace with your database user name-->
DB_PWD=<!--replace with your database password-->
DB_NAME=<!--replace with your database name-->

create a db.ts file to create database object as shown below

import { Kysely, PostgresDialect } from 'kysely';

import { Pool } from 'pg';
import {DB} from '../../node_modules/kysely-codegen/dist/db';

const db = new Kysely<DB>({dialect:new PostgresDialect({
pool: new Pool({
database: process.env.DB_NAME,
host: process.env.DB_HOST,
user: process.env.DB_USER,
port: 5432,
max: 10,
password:process.env.DB_PASS
})
})});

export default db;

Since Kysely is ORM, we need to define types which will be used to query from database (SELECT, INSERT, UPDATE and DELETE). These are just like Entities in Java Eco System (Hibernate, JPA etc.,)

We can create these types manually or we can auto-generate.

you can follow below documentation to auto-generate types

After generating types, you can use query as shown below.

export default async function findUserByUserName(userName: string) {
return await db
.selectFrom("AUTOGENERATED_TYPE")
.where("AUTOGENERATED_TYPE.AUTOGENERATED_TYPE_VARIABLE", "=", userName)
.selectAll()
.executeTakeFirst();
}

It will result an user.

For more details visit https://kysely.dev/docs/intro

For more such content, visit https://yoursiva.com/

Thats it. Happy Coding!! :)

--

--

No responses yet