
A comprehensive guide to integrating Kysely, a type-safe SQL query builder, with your Next.js application.
Kysely is a type-safe TypeScript SQL query builder that provides excellent autocomplete and compile-time type checking for your database queries. Unlike ORMs, it doesn't abstract SQL - it embraces it while adding type safety.
- Next.js 13+ with App Router
- PostgreSQL database
- Node.js 18+
Package breakdown:
- `kysely` - The query builder
- `pg` - PostgreSQL driver
- `dotenv` - Environment variable loader
- `@types/pg` - TypeScript types for pg
- `kysely-codegen` - Auto-generate types from your database
Create `.env.local` in your project root:
Important Notes:
- Use `.env.local` for local development (not committed to git)
- Use `.env` for shared defaults (can be committed)
- Never commit sensitive credentials
Special Characters in Password:
If your password contains special characters, URL-encode them:
- `@` → `%40`
- `:` → `%3A`
- `/` → `%2F`
- `#` → `%23`
- `?` → `%3F`
- `&` → `%26`
Example:
Create `src/lib/db/index.ts`:
Create `migrations/001_initial.sql`:
Apply the migration:
Add script to `package.json`:
Generate types:
This creates `src/lib/db/types.ts` with your database schema as TypeScript types.
Create `src/app/actions/users.ts`:
Create `src/lib/db/migrator.ts`:
Create `src/lib/db/migrations/001_create_organizations.ts`:
Update `package.json`:
Run migrations:
Solution: Use npx or install globally
Solutions:
1. Check password is not empty
2. URL-encode special characters in password
3. Remove quotes from DATABASE_URL
4. Ensure no whitespace around `=` in .env file
Solution: Generate types first
Solution: Import dotenv at the top of your file
Solution: Check your TypeScript paths in `tsconfig.json`
Already configured in our setup with `max: 10` connections.
- [Kysely Documentation](https://kysely.dev)
- [Kysely GitHub](https://github.com/kysely-org/kysely)
- [Next.js Documentation](https://nextjs.org/docs)
- [PostgreSQL Documentation](https://www.postgresql.org/docs/)
Kysely provides type-safe database queries while keeping you close to SQL. It's an excellent choice for Next.js applications where you want:
- Full type safety
- SQL control
- Great TypeScript autocomplete
- No ORM magic
- Performance optimization
Happy querying! 🚀