Cloudflare Docs
D1
Visit D1 on GitHub
Set theme to dark (⇧+D)

Query D1 from Hono

Query D1 from the Hono web framework

Hono is a fast web framework for building API-first applications, and it includes first-class support for both Workers and Pages.

When using Workers:

If you are using Pages Functions:

The following examples show how to access a D1 database bound to DB from both a Workers script and a Pages Function:

src/worker.ts
import { Hono } from 'hono'
// This ensures c.env.DB is correctly typed
type Bindings = {
DB: D1Database
}
const app = new Hono<{ Bindings: Bindings }>()
// Accessing D1 is via the c.env.YOUR_BINDING property
app.get("/query/users/:id", async (c) => {
const userId= c.req.param("id")
try {
let { results } = await c.env.DB.prepare("SELECT * FROM users WHERE user_id = ?").bind(userId).all()
return c.json(results)
} catch (e) {
return c.json({err: e}, 500)
}
})
// Export our Hono app: Hono automatically exports a
// Workers 'fetch' handler for you
export default app
functions/api/[[route]].ts
import { Hono } from 'hono'
import { handle } from 'hono/cloudflare-pages'
const app = new Hono().basePath('/api')
// Accessing D1 is via the c.env.YOUR_BINDING property
app.get("/query/users/:id", async (c) => {
const userId= c.req.param("id")
try {
let { results } = await c.env.DB.prepare("SELECT * FROM users WHERE user_id = ?").bind(userId).all()
return c.json(results)
} catch (e) {
return c.json({err: e}, 500)
}
})
// Export the Hono instance as a Pages onRequest function
export const onRequest = handle(app)