Knex.js — Flexible SQL Query Builder for Node.js
A batteries-included SQL query builder for PostgreSQL, MySQL, SQLite, and Oracle with a fluent API, migration framework, and connection pooling.
What it is
Knex.js is one of the most widely used SQL query builders for Node.js. It provides a chainable, fluent JavaScript API for constructing parameterized SQL queries that work across PostgreSQL, MySQL, MariaDB, SQLite3, Oracle, and Amazon Redshift. Rather than writing raw SQL strings, developers compose queries programmatically while Knex handles dialect-specific differences.
Knex serves as the foundation for higher-level ORMs like Objection.js and Bookshelf. It is well suited for backend developers who want more control than a full ORM provides but still want protection against SQL injection and cross-dialect portability.
How it saves time or tokens
Knex eliminates the need to manually write dialect-specific SQL for each database. A single query definition works across PostgreSQL, MySQL, and SQLite without modification. The built-in migration framework handles schema versioning, and connection pooling via tarn.js manages database connections automatically. This reduces boilerplate code and context-switching between SQL dialects when working with AI coding assistants.
How to use
- Install Knex and your database driver:
npm install knex pg(or mysql2, sqlite3). - Initialize configuration:
npx knex initcreates aknexfile.jswith connection settings. - Create and run migrations:
npx knex migrate:make create_usersthennpx knex migrate:latest. - Use the fluent API to build queries in your application code.
Example
const knex = require('knex')({
client: 'pg',
connection: 'postgres://localhost/mydb'
});
// Select with joins
const users = await knex('users')
.join('orders', 'users.id', 'orders.user_id')
.select('users.name', knex.raw('SUM(orders.total) as total_spent'))
.groupBy('users.id')
.having('total_spent', '>', 100);
// Migration example
exports.up = function(knex) {
return knex.schema.createTable('users', (table) => {
table.increments('id');
table.string('name').notNullable();
table.string('email').unique();
table.timestamps(true, true);
});
};
Related on TokRepo
- Database tools for AI workflows -- browse database utilities and ORMs curated on TokRepo.
- Automation tools -- discover tools that automate repetitive backend tasks.
Common pitfalls
- Forgetting to return the promise from migration functions causes silent failures. Always
return knex.schema...inupanddown. - Connection pool exhaustion happens when queries are not properly awaited or connections are not released. Set
pool.minandpool.maxin your knexfile. - Knex does not validate your SQL logic. A query that runs on PostgreSQL may fail on SQLite due to unsupported features like
RETURNING.
Frequently Asked Questions
Knex.js supports PostgreSQL, MySQL, MariaDB, SQLite3, Oracle, and Amazon Redshift. Each dialect has its own driver that Knex uses to translate the fluent API into the correct SQL syntax.
Knex is a query builder, not a full ORM. It does not define models or relationships. Instead it provides a programmatic way to write SQL. Prisma and Sequelize add schema modeling, validation, and relationship management on top of query construction.
Yes. Knex includes a built-in migration framework. You create migration files with `knex migrate:make`, define up and down functions for schema changes, and run them with `knex migrate:latest`. Migrations execute inside transactions for atomicity.
Yes. Knex uses tarn.js for connection pooling and supports transactions, streaming, and parameterized queries to prevent SQL injection. It is used in production by many Node.js applications and serves as the query layer for ORMs like Objection.js.
Knex provides built-in TypeScript type definitions. You can type your table interfaces and pass them as generics to queries: `knex<User>('users').where('id', 1)`. The knexfile can also be written in TypeScript with ts-node.
Citations (3)
- Knex.js GitHub— Knex.js supports PostgreSQL, MySQL, MariaDB, SQLite3, Oracle, and Amazon Redshif…
- Knex.js Documentation— Connection pooling is handled by tarn.js
- Objection.js Documentation— Knex serves as the query layer for Objection.js ORM
Related on TokRepo
Discussion
Related Assets
NAPI-RS — Build Node.js Native Addons in Rust
Write high-performance Node.js native modules in Rust with automatic TypeScript type generation and cross-platform prebuilt binaries.
Mamba — Fast Cross-Platform Package Manager
A drop-in conda replacement written in C++ that resolves environments in seconds instead of minutes.
Plasmo — The Browser Extension Framework
Build, test, and publish browser extensions for Chrome, Firefox, and Edge using React or Vue with hot-reload and automatic manifest generation.