0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Cloudflare D1とnext-on-pageでenv.DBを渡したいがタイプエラーになる Drizzle hono

Last updated at Posted at 2025-03-30

はじめに

CloudflareのD1をhonoのAPIで読み取るのに時間がかかったのでまとめます

問題

今回next-on-pageを利用していたのでc.env.DBからは読み込めないようなので以下のコードを書いた

import { users } from "@/db/schema";
import { drizzle } from "drizzle-orm/d1";
import { Hono } from "hono";
import { handle } from "hono/vercel";

export const runtime = "edge";

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      DB: D1Database;
    }
  }
}

const app = new Hono().basePath("/api");

app.get("/ping", (c) => {
  return c.text("pong");
});

app.get("/query/customers", async (c) => {
  const db = drizzle(process.env.DB);
  const result = await db.select().from(users).all();
  return c.json(result);
});

export const GET = handle(app);

しかしVSCodeではタイプエラーが発生

image.png

ES2015 module syntax is preferred over namespaces

しかたなくenv.d.tsに移動してみましたが依然としてprocess.env.DBからエラーが出ました。

解決策

型を上手く合わせることで動くようになりました

import { users } from "@/db/schema";
import { drizzle } from "drizzle-orm/d1";
import { Hono } from "hono";
import { handle } from "hono/vercel";

export const runtime = "edge";
const app = new Hono().basePath("/api");

app.get("/ping", (c) => {
  return c.text("pong");
});

app.get("/query/customers", async (c) => {
  console.log(c.env);
  const db = drizzle(process.env.DB as unknown as D1Database);
  const result = await db.select().from(users).all();
  return c.json(result);
});

export const GET = handle(app);

おわりに

かなり沼ってしまったのですが一旦これでも良いのではないかと思いました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?