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:
- Ensure you have configured your Wrangler configuration file to bind your D1 database to your Worker.
- You can access your D1 databases via Hono's
Context
↗ parameter: bindings ↗ are exposed oncontext.env
. If you configured a binding namedDB
, then you would access D1 Workers Binding API methods viac.env.DB
. - Refer to the Hono documentation for Cloudflare Workers ↗.
If you are using Pages Functions:
- Bind a D1 database to your Pages Function.
- Pass the
--d1 BINDING_NAME=DATABASE_ID
flag towrangler dev
when developing locally.BINDING_NAME
should match what call in your code, andDATABASE_ID
should match thedatabase_id
defined in your Wrangler configuration file: for example,--d1 DB=xxxx-xxxx-xxxx-xxxx-xxxx
. - Refer to the Hono guide for Cloudflare Pages ↗.
The following examples show how to access a D1 database bound to DB
from both a Workers script and a Pages Function:
import { Hono } from "hono";
// This ensures c.env.DB is correctly typedtype Bindings = { DB: D1Database;};
const app = new Hono<{ Bindings: Bindings }>();
// Accessing D1 is via the c.env.YOUR_BINDING propertyapp.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.message }, 500); }});
// Export our Hono app: Hono automatically exports a// Workers 'fetch' handler for youexport default app;
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 propertyapp.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.message }, 500); }});
// Export the Hono instance as a Pages onRequest functionexport const onRequest = handle(app);