knex is a free, open source databases project written in JavaScript and released under MIT. It has 20,344 GitHub stars, 2,222 forks and 751 open issues, and was last pushed 3 months ago. On this registry it ranks #30 of 81 tracked projects in Databases, with 5 head-to-head comparisons available.

What is knex?

Knex is an open-source SQL query builder for Node.js that targets PostgreSQL, MariaDB, MySQL, CockroachDB, Microsoft SQL Server, SQLite3 and Oracle, and it is aimed at JavaScript and TypeScript developers who need one query API across several database engines instead of hand-written SQL per dialect.

What it is

Knex is a batteries-included, multi-dialect query builder for Node.js, distributed as the knex package on npm under the MIT licence. It supports Node.js 16 and later and offers both a promise API and a callback API, with TypeScript definitions such as import { Knex, knex } from 'knex'. The project lives in the JavaScript and npm ecosystem, keeps its documentation at knexjs.org, and lists its topic set as javascript, knex, mysql, postgresql, sql, and sqlite3. It also covers Oracle Wallet Authentication alongside the more common engines, and it ships a thorough test suite run through GitHub Actions.

The concrete problem it solves is dialect drift. Application code written against one database engine usually has to be rewritten, or wrapped in conditional string building, when the same application must also run on another engine. Knex replaces that hand-assembled SQL with a single builder API that emits the correct SQL for the configured client, so the same calls to knex('users').insert(...), .join('accounts', 'users.id', 'accounts.user_id') and .select('users.user_name as user', 'accounts.account_name as account') produce engine-appropriate statements. To inspect what a given query will emit, the project points to Knex Query Lab.

Key capabilities

  • Multi-dialect support across PostgreSQL, MariaDB, MySQL, CockroachDB, MSSQL, SQLite3 and Oracle, including Oracle Wallet Authentication.
  • Transactions, documented in the guide at knexjs.org/guide/transactions.html.
  • Connection pooling, configured through the pool option in the guide.
  • Streaming queries, exposed through the interfaces documented under streams.
  • Both a promise API and a callback API for the same query builder.
  • Schema building through knex.schema.createTable('users', (table) => { ... }), including column helpers such as table.increments('id') and foreign keys via table.integer('user_id').unsigned().references('users.id').
  • A published plugin and tools list in ECOSYSTEM.md, a recipes wiki for common problems, an UPGRADING.md migration guide for older versions, and support through the GitHub issues page and a Gitter channel.

Who uses it and how

  • Node.js backend teams that must serve more than one database engine, using one builder layer rather than separate query code per engine.
  • Teams that want a model layer above the query layer, through the Knex-based ORMs the README names: objection.js, mikro-orm and bookshelfjs.
  • Developers prototyping against a local file database, as in the README example that configures client: 'sqlite3' with connection: { filename: './data.db' } before creating tables and inserting rows.
  • Contributors building from source, who need Node.js 16 or later, Python 3.x with setuptools installed for native dependencies such as better-sqlite3, and, on Windows, Visual Studio Build Tools with the "Desktop development with C++" workload.

Getting started

Install the knex package from npm together with a driver for the target engine, then create an instance from a config object such as { client: 'sqlite3', connection: { filename: './data.db' } }. Full documentation and further examples are published at knexjs.org.

How it compares

The tools the facts place nearest to Knex are objection.js, mikro-orm and bookshelfjs, which are Object Relational Mappers built on top of Knex rather than alternatives to it, so Knex sits beneath them as the query layer. For verifying the generated SQL directly, Knex Query Lab occupies a neighbouring role as an inspection tool for the same queries.

When to use it — and when not to

Knex is a library, not a hosted service, so a team adopting it must already run whichever database engine it points at and manage that engine, its credentials and its backups. Teams that want a full model layer with entities and relations should look at the ORMs named above, and teams outside Node.js cannot use it at all. The costs are visible in the project's own setup notes, which require a Python 3.x toolchain with setuptools and, on Windows, C++ build tools to compile native dependencies, plus a repository that carries 751 open issues.

project readme (upstream, from github) — read inline

knex.js

npm version npm downloads codecov Dependencies Status Gitter chat

A SQL query builder that is flexible, portable, and fun to use!

A batteries-included, multi-dialect (PostgreSQL, MariaDB, MySQL, CockroachDB, MSSQL, SQLite3, Oracle (including Oracle Wallet Authentication)) query builder for Node.js, featuring:

Node.js versions 16+ are supported.

You can report bugs and discuss features on the GitHub issues page or send tweets to @kibertoad.

For support and questions, join our Gitter channel.

For knex-based Object Relational Mapper, see:

To see the SQL that Knex will generate for a given query, you can use Knex Query Lab

Local Development Setup

Prerequisites

  • Node.js 16+

  • Python 3.x with setuptools installed (required for building native dependencies like better-sqlite3)

    Python 3.12+ removed the built-in distutils module. If you encounter a ModuleNotFoundError: No module named 'distutils' error during npm install, install setuptools for the Python version used by node-gyp:

    pip install setuptools
    
  • Windows only: Visual Studio Build Tools with the "Desktop development with C++" workload

Install dependencies

npm install

Examples

We have several examples on the website. Here is the first one to get you started:

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);
}

TypeScript example

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();
  });

Usage as ESM module

If you are launching your Node application with --experimental-modules, knex.mjs should be picked up automatically and named ESM import should work out-of-the-box. Otherwise, if you want to use named imports, you'll have to import knex like this:

import { knex } from 'knex/knex.mjs';

You can also just do the default import:

import knex from 'knex';

If you are not using TypeScript and would like the IntelliSense of your IDE to work correctly, it is recommended to set the type explicitly:

/**
 * @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();

Frequently asked questions

Is knex free to use?

knex is open source under the MIT licence. There is no licence fee and no seat count — you can self-host it or, where the project offers one, pay a vendor for a managed version instead.

What does knex do?

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

What is knex written in?

knex is primarily written in JavaScript. Its source is publicly available at https://github.com/knex/knex, and it has 20,344 GitHub stars.