Skip to content

Guide · Open source

How to use knex: query SQL databases from Node.js

Updated · written with AI from the project's own documentation and checked against our catalogue data

Knex is a query builder for Node.js. Instead of writing raw SQL strings, you describe queries as JavaScript code, and the same code can run against PostgreSQL, MySQL, MariaDB, CockroachDB, SQL Server, SQLite3 and Oracle. This guide shows how to set it up, run a first example, and use transactions, streaming and TypeScript.

knexknex/knex · ★ 20.3k · MIT

Quick start

  1. 1Check prerequisites. Confirm you have Node.js 16 or later. On Windows, or if a native dependency fails to build, install the listed build tools.
  2. 2Install knex. Add knex to your project with your package manager, along with the database driver for your engine.
  3. 3Configure a client. Create an instance with a client name such as sqlite3 and a connection object.
  4. 4Create tables. Use knex.schema.createTable with a callback to define columns.
  5. 5Run queries. Insert, select and join rows using the chainable query builder, then await the result.
  6. 6Use transactions and close the pool. Group related work in a transaction for consistency, and call destroy() when the program finishes.

What knex is and who it is for

Knex is a multi-dialect query builder rather than a full ORM. It does not provide models or relationships; the project points to separate ORMs such as Objection.js, MikroORM and Bookshelf for that.

It suits Node.js developers who need to talk to a SQL database from application code, and teams that may switch database engines later. You still need to understand SQL, because the builder assumes that knowledge.

  • Supported databases: PostgreSQL, MariaDB, MySQL, CockroachDB, MSSQL, SQLite3 and Oracle (including Oracle Wallet Authentication)
  • Built-in features: transactions, connection pooling, streaming queries, and both promise and callback APIs
  • Licence: MIT

What you need before installing knex

Knex runs on Node.js 16 or later. If you use a driver that builds native code, such as better-sqlite3, you also need Python 3.x with setuptools.

  • Node.js 16+
  • Python 3.x with setuptools (for native dependencies such as better-sqlite3)
  • Windows only: Visual Studio Build Tools with the "Desktop development with C++" workload
  • If npm install fails with a distutils error on Python 3.12+, install setuptools for the Python version node-gyp uses
pip install setuptools

Install dependencies and run a first query

The README's setup command installs the project's dependencies in a cloned repository. Your own application installs knex with your package manager, and you also install the database driver for the engine you use.

The example below uses SQLite3, which stores data in a local file. It creates two tables, inserts rows, joins them and maps over the results. The query builder calls are awaited, so run it inside an async function or an ES module with top-level await.

const knex = require('knex')({ client: 'sqlite3', connection: { filename: './data.db', }, }); try { // Create a table await knex.schema .createTable('users', (table) => { table.increments('id'); table.string('user_name'); }) // ...and another .createTable('accounts', (table) => { table.increments('id'); table.string('account_name'); table.integer('user_id').unsigned().references('users.id'); }); // Then query the table... const insertedRows = await knex('users').insert({ user_name: 'Tim' }); // ...and using the insert id, insert into the other table. await knex('accounts').insert({ account_name: 'knex', user_id: insertedRows[0], }); // Query both of the rows. const selectedRows = await knex('users') .join('accounts', 'users.id', 'accounts.user_id') .select('users.user_name as user', 'accounts.account_name as account'); // map over the results const enrichedRows = selectedRows.map((row) => ({ ...row, active: true })); // Finally, add a catch statement } catch (e) { console.error(e); }

Use knex with TypeScript

Knex ships typings. You can type the configuration as Knex.Config and type a table's rows with an interface. Call destroy() when you are finished so the connection pool closes.

The SQLite setting useNullAsDefault is set to true in the example, as the source shows it.

  • Import with: import { Knex, knex } from 'knex'
  • Pass a generic such as knexInstance<User>('users') to type query results
import { Knex, knex } from 'knex'; interface User { id: number; age: number; name: string; active: boolean; departmentId: number; } const config: Knex.Config = { client: 'sqlite3', connection: { filename: './data.db', }, useNullAsDefault: true, }; const knexInstance = knex(config); knexInstance<User>('users') .select() .then((users) => { console.log(users); }) .catch((err) => { console.error(err); }) .finally(() => { knexInstance.destroy(); });

Import knex as an ES module

If you launch Node with --experimental-modules, knex.mjs is picked up automatically and named ESM imports work. Otherwise you can import the named export from the knex.mjs file, or use the default import.

If you are not using TypeScript and want IDE autocomplete, the README suggests annotating the instance with a JSDoc type. The example also calls database.migrate.latest(), which the source shows without further explanation.

import { knex } from 'knex/knex.mjs'; // or import knex from 'knex'; /** * @type {Knex} */ const database = knex({ client: 'mysql', connection: { host: '127.0.0.1', user: 'your_database_user', password: 'your_database_password', database: 'myapp_test', }, }); database.migrate.latest();

Where to find more help

The full documentation at knexjs.org covers getting started. The README also links a plugins and tools list, a recipes wiki for specific problems, and a migration guide for upgrading from older versions. To see the SQL knex generates for a query, the README mentions the third-party Knex Query Lab tool.

Bugs and feature discussions go to the GitHub issues page. Support questions can be asked on the project's Gitter channel.

  • Full documentation: knexjs.org
  • Plugins and tools: ECOSYSTEM.md in the repository
  • Recipes: the GitHub wiki
  • Upgrading: UPGRADING.md in the repository

What people use it for

  • Storing user and account records in a SQL database from a Node.js API
  • Writing queries that can move from SQLite during development to PostgreSQL or MySQL in production
  • Streaming large query results instead of loading them all into memory
  • Running grouped database changes inside a transaction

Frequently asked questions

Is knex free to use?

Yes. The knex project is licensed under the MIT licence, as listed in its repository.

What do I need to install knex?

You need Node.js 16 or later and install knex with npm. Python 3.x with setuptools and, on Windows, Visual Studio Build Tools with the C++ workload are needed for native dependencies such as better-sqlite3.

Which databases does knex support?

The README lists PostgreSQL, MariaDB, MySQL, CockroachDB, MSSQL, SQLite3 and Oracle, including Oracle Wallet Authentication.

Is knex an ORM?

No. Knex is a query builder. For models and relationships, the README points to Objection.js, MikroORM and Bookshelf.

How does knex compare to Prisma, Sequelize or Kysely?

The source lists these as comparable projects but does not compare their features. Check each project's documentation against your needs, such as whether you want an ORM with models or a query builder.

Why does npm install fail with a distutils error?

On Python 3.12 and later, distutils is no longer built in. Install setuptools for the Python version node-gyp uses with pip install setuptools, then run npm install again.

New agent skills, repos and AI tools — every week

The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.

Our verdict

Knex suits Node.js developers who want to write SQL-style queries in JavaScript and may switch between database engines. If you want an ORM with models and relationships, or you have no SQL knowledge yet, pick a tool built for that instead.

Install options & downloads