Home Blog Talks

How to Use Knex with Cloudflare D1 Database Outside of Cloudflare?

2024-09-07

Background

Cloudflare D1 is a distributed database based on SQLite, offering good read and write performance globally, while being cost-effective and providing a generous free tier.

Knex is a lightweight yet powerful database query library that supports local SQLite.

Combining Cloudflare D1 and Knex can effectively improve development efficiency for small projects and reduce service costs.

Solution

Based on cloudflare-d1-http-knex

Installation

npm install cloudflare-d1-http-knex

# or
bun add cloudflare-d1-http-knex

Usage

import { createConnection } from 'cloudflare-d1-http-knex';

// The connection function returns a Knex instance
const connection = createConnection({
  account_id: 'account_id',
  database_id: 'database_id',
  key: 'key',
});

const query = await connection('table_name').select('*');

Unit Testing

import { createConnection } from 'cloudflare-d1-http-knex'
import { mockedFetch } from 'cloudflare-d1-http-knex/mock'

const db = createConnection({
  account_id: 'xxxx',
  database_id: 'xxxx',
  key: 'xxxx',
  mockedFetch, // Using mocked fetch, it won't connect to real D1 database.
})

await db.raw('SELECT 1+1')
Back to all posts