Interacting with SQL using Knex

Updated: 03 September 2023

Knex is a library for Node.js which supports for a variety of SQL databases and allows us to generate and run queries against them

Knex as a Query Builder

We can use Knex to generate SQL queries for a database using something like the following structure:

1
const knex = require('knex')({
2
client: 'pg',
3
})
4
5
const query = knex('users').where({ username: 'bob' }).toQuery()
6
7
console.log(query) // select * from "users" where "username" = 'bob'

We can use Knex using TS in a more practical sense like such:

1
const createUser = (username: string) => {
2
return knex('users').insert({ username }).returning('*').toQuery()
3
}
4
5
const getUser = (username: string) => {
6
return knex('users').where({ username }).toQuery()
7
}