mcpField
H
hono-cloudflare

hono-cloudflare

github.com/bobmatnycクラウド・DevOps78626 回インストール15 週間前に更新
リポジトリ

hono-cloudflare について

Hono on Cloudflare Workers は、Cloudflare エコシステムで Hono アプリを構築するためのスキルです。型付きバインディング、ストレージやコンピューティング機能、静的アセット、Pages、イベントハンドラーを扱います。

主な機能

  1. 01Workers のネイティブ対応
  2. 02型付き環境バインディング
  3. 03KV、D1、R2、Durable Objects
  4. 04静的アセットと Pages
  5. 05キューとスケジュール処理

活用シーン

  1. 01エッジ API の構築
  2. 02D1 によるサーバーレス SQLite の利用
  3. 03Durable Objects によるリアルタイムアプリの作成
  4. 04R2 を使ったファイル保存

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill hono-cloudflare

インストール後、Claude Code で/hono-cloudflareを入力して読み込まれたか確認します。

同梱ファイルmetadata.json

詳細

Cloudflare Workers 上の Hono

概要

Hono はもともと Cloudflare Workers 向けに構築されており、KV、D1、R2、Durable Objects、Queues など、Cloudflare エコシステム全体を第一級でサポートしています。

主な機能:

  • Workers のネイティブサポート
  • 型安全なバインディングアクセス
  • KV、D1、R2、Durable Objects との統合
  • 静的アセットの配信
  • Cloudflare Pages のサポート
  • Queue およびスケジュールされたハンドラー

このスキルを使用する場面

次のような場合に、Cloudflare 上で Hono を使用します:

  • グローバルに分散されたエッジ API を構築する
  • D1 を使ったサーバーレス SQLite が必要
  • Durable Objects を使ったリアルタイムアプリを構築する
  • R2 を使ってファイルを保存する
  • KV を使った高速なキー・バリューストレージが必要
  • フルスタックアプリを Pages にデプロイする

クイックスタート

新しいプロジェクトの作成
npm create hono@latest my-app

# Select: cloudflare-workers

cd my-app
npm install
npm run dev
プロジェクト構成
my-app/
├── src/
│   └── index.ts         # Main entry point
├── wrangler.toml        # Cloudflare configuration
├── package.json
└── tsconfig.json
基本的なアプリケーション
// src/index.ts
import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => c.text('Hello Cloudflare Workers!'))

export default app
デプロイ
# Deploy to Cloudflare
npx wrangler deploy

# Local development
npx wrangler dev

環境バインディング

型付きバインディング
import { Hono } from 'hono'

// Define your bindings
type Bindings = {
  // Environment variables
  API_KEY: string
  DATABASE_URL: string

  // KV Namespaces
  MY_KV: KVNamespace

  // D1 Databases
  DB: D1Database

  // R2 Buckets
  BUCKET: R2Bucket

  // Durable Objects
  COUNTER: DurableObjectNamespace

  // Queues
  MY_QUEUE: Queue
}

const app = new Hono<{ Bindings: Bindings }>()

app.get('/config', (c) => {
  // Fully typed access
  const apiKey = c.env.API_KEY
  return c.json({ configured: !!apiKey })
})

export default app
wrangler.toml の設定
name = "my-app"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[vars]
API_KEY = "your-api-key"  # pragma: allowlist secret

[[kv_namespaces]]
binding = "MY_KV"
id = "your-kv-id"

[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "your-d1-id"

[[r2_buckets]]
binding = "BUCKET"
bucket_name = "my-bucket"

[[queues.producers]]
binding = "MY_QUEUE"
queue = "my-queue"

KV ストレージ

基本操作
type Bindings = {
  CACHE: KVNamespace
}

const app = new Hono<{ Bindings: Bindings }>()

// Get value
app.get('/cache/:key', async (c) => {
  const key = c.req.param('key')
  const value = await c.env.CACHE.get(key)

  if (!value) {
    return c.json({ error: 'Not found' }, 404)
  }

  return c.json({ key, value })
})

// Get JSON value
app.get('/cache/:key/json', async (c) => {
  const key = c.req.param('key')
  const value = await c.env.CACHE.get(key, 'json')

  return c.json({ key, value })
})

// Set value
app.put('/cache/:key', async (c) => {
  const key = c.req.param('key')
  const body = await c.req.json()

  await c.env.CACHE.put(key, JSON.stringify(body), {
    expirationTtl: 3600  // 1 hour
  })

  return c.json({ success: true })
})

// Delete value
app.delete('/cache/:key', async (c) => {
  const key = c.req.param('key')
  await c.env.CACHE.delete(key)

  return c.json({ success: true })
})

// List keys
app.get('/cache', async (c) => {
  const prefix = c.req.query('prefix') || ''
  const list = await c.env.CACHE.list({ prefix, limit: 100 })

  return c.json({ keys: list.keys })
})
メタデータ付き KV
interface UserMeta {
  createdAt: string
  role: string
}

app.put('/users/:id', async (c) => {
  const id = c.req.param('id')
  const user = await c.req.json()

  await c.env.CACHE.put(`user:${id}`, JSON.stringify(user), {
    metadata: {
      createdAt: new Date().toISOString(),
      role: user.role
    } as UserMeta
  })

  return c.json({ success: true })
})

app.get('/users/:id', async (c) => {
  const id = c.req.param('id')
  const { value, metadata } = await c.env.CACHE.getWithMetadata<UserMeta>(`user:${id}`, 'json')

  if (!value) {
    return c.json({ error: 'Not found' }, 404)
  }

  return c.json({ user: value, metadata })
})

D1 データベース

基本的なクエリ
type Bindings = {
  DB: D1Database
}

const app = new Hono<{ Bindings: Bindings }>()

// Select all
app.get('/users', async (c) => {
  const { results } = await c.env.DB
    .prepare('SELECT * FROM users ORDER BY created_at DESC')
    .all()

  return c.json({ users: results })
})

// Select one
app.get('/users/:id', async (c) => {
  const id = c.req.param('id')
  const user = await c.env.DB
    .prepare('SELECT * FROM users WHERE id = ?')
    .bind(id)
    .first()

  if (!user) {
    return c.json({ error: 'Not found' }, 404)
  }

  return c.json({ user })
})

// Insert
app.post('/users', async (c) => {
  const { name, email } = await c.req.json()

  const result = await c.env.DB
    .prepare('INSERT INTO users (name, email) VALUES (?, ?)')
    .bind(name, email)
    .run()

  return c.json({
    success: result.success,
    id: result.meta.last_row_id
  }, 201)
})

// Update
app.put('/users/:id', async (c) => {
  const id = c.req.param('id')
  const { name, email } = await c.req.json()

  const result = await c.env.DB
    .prepare('UPDATE users SET name = ?, email = ? WHERE id = ?')
    .bind(name, email, id)
    .run()

  return c.json({ success: result.success })
})

// Delete
app.delete('/users/:id', async (c) => {
  const id = c.req.param('id')

  const result = await c.env.DB
    .prepare('DELETE FROM users WHERE id = ?')
    .bind(id)
    .run()

  return c.json({ success: result.success })
})
バッチ操作
app.post('/users/batch', async (c) => {
  const { users } = await c.req.json()

  const statements = users.map((user: { name: string; email: string }) =>
    c.env.DB
      .prepare('INSERT INTO users (name, email) VALUES (?, ?)')
      .bind(user.name, user.email)
  )

  const results = await c.env.DB.batch(statements)

  return c.json({
    success: results.every(r => r.success),
    count: results.length
  })
})

R2 オブジェクトストレージ

type Bindings = {
  BUCKET: R2Bucket
}

const app = new Hono<{ Bindings: Bindings }>()

// Upload file
app.post('/files/:key', async (c) => {
  const key = c.req.param('key')
  const body = await c.req.arrayBuffer()
  const contentType = c.req.header('Content-Type') || 'application/octet-stream'

  await c.env.BUCKET.put(key, body, {
    httpMetadata: { contentType }
  })

  return c.json({ success: true, key })
})

// Download file
app.get('/files/:key', async (c) => {
  const key = c.req.param('key')
  const object = await c.env.BUCKET.get(key)

  if (!object) {
    return c.json({ error: 'Not found' }, 404)
  }

  const headers = new Headers()
  headers.set('Content-Type', object.httpMetadata?.contentType || 'application/octet-stream')
  headers.set('ETag', object.httpEtag)

  return new Response(object.body, { headers })
})

// Delete file
app.delete('/files/:key', async (c) => {
  const key = c.req.param('key')
  await c.env.BUCKET.delete(key)

  return c.json({ success: true })
})

// List files
app.get('/files', async (c) => {
  const prefix = c.req.query('prefix') || ''
  const list = await c.env.BUCKET.list({ prefix, limit: 100 })

  return c.json({
    objects: list.objects.map(obj => ({
      key: obj.key,
      size: obj.size,
      uploaded: obj.uploaded
    }))
  })
})

Durable Objects

Durable Object の定義
// src/counter.ts
export class Counter {
  private state: DurableObjectState
  private value: number = 0

  constructor(state: DurableObjectState) {
    this.state = state
  }

  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url)

    // Load value from storage
    this.value = await this.state.storage.get('value') || 0

    switch (url.pathname) {
      case '/increment':
        this.value++
        await this.state.storage.put('value', this.value)
        return new Response(String(this.value))

      case '/decrement':
        this.value--
        await this.state.storage.put('value', this.value)
        return new Response(String(this.value))

      case '/value':
        return new Response(String(this.value))

      default:
        return new Response('Not found', { status: 404 })
    }
  }
}
Hono での使用
import { Hono } from 'hono'

type Bindings = {
  COUNTER: DurableObjectNamespace
}

const app = new Hono<{ Bindings: Bindings }>()

app.get('/counter/:name/increment', async (c) => {
  const name = c.req.param('name')
  const id = c.env.COUNTER.idFromName(name)
  const stub = c.env.COUNTER.get(id)

  const response = await stub.fetch('http://counter/increment')
  const value = await response.text()

  return c.json({ name, value: parseInt(value) })
})

app.get('/counter/:name', async (c) => {
  const name = c.req.param('name')
  const id = c.env.COUNTER.idFromName(name)
  const stub = c.env.COUNTER.get(id)

  const response = await stub.fetch('http://counter/value')
  const value = await response.text()

  return c.json({ name, value: parseInt(value) })
})

export default app
export { Counter }
Durable Objects 用の wrangler.toml
[[durable_objects.bindings]]
name = "COUNTER"
class_name = "Counter"

[[migrations]]
tag = "v1"
new_classes = ["Counter"]

Queues

プロデューサー
type Bindings = {
  MY_QUEUE: Queue
}

const app = new Hono<{ Bindings: Bindings }>()

app.post('/tasks', async (c) => {
  const task = await c.req.json()

  await c.env.MY_QUEUE.send({
    type: 'process',
    data: task
  })

  return c.json({ queued: true })
})

// Batch send
app.post('/tasks/batch', async (c) => {
  const { tasks } = await c.req.json()

  await c.env.MY_QUEUE.sendBatch(
    tasks.map((task: any) => ({
      body: { type: 'process', data: task }
    }))
  )

  return c.json({ queued: tasks.length })
})
コンシューマー
export default {
  fetch: app.fetch,

  async queue(batch: MessageBatch, env: Bindings): Promise<void> {
    for (const message of batch.messages) {
      const { type, data } = message.body as { type: string; data: any }

      try {
        // Process message
        console.log(`Processing ${type}:`, data)
        message.ack()
      } catch (error) {
        message.retry()
      }
    }
  }
}

静的アセット

wrangler.toml
name = "my-app"
main = "src/index.ts"
compatibility_date = "2024-01-01"

# Serve static files from public directory
assets = { directory = "public" }
ルートハンドラーとの併用
import { Hono } from 'hono'
import { serveStatic } from 'hono/cloudflare-workers'

const app = new Hono()

// Serve static files
app.use('/static/*', serveStatic({ root: './' }))

// API routes
app.get('/api/hello', (c) => c.json({ hello: 'world' }))

export default app

スケジュールイベント(Cron)

import { Hono } from 'hono'

const app = new Hono()

// Regular routes...

export default {
  fetch: app.fetch,

  async scheduled(
    event: ScheduledEvent,
    env: Bindings,
    ctx: ExecutionContext
  ): Promise<void> {
    switch (event.cron) {
      case '0 * * * *':  // Every hour
        await hourlyTask(env)
        break

      case '0 0 * * *':  // Daily at midnight
        await dailyTask(env)
        break
    }
  }
}

async function hourlyTask(env: Bindings) {
  console.log('Running hourly task')
}

async function dailyTask(env: Bindings) {
  console.log('Running daily task')
}
Cron 用の wrangler.toml
[triggers]
crons = ["0 * * * *", "0 0 * * *"]

Cloudflare Pages

pages/functions ディレクトリ
my-app/
├── public/              # Static assets
│   ├── index.html
│   └── styles.css
└── functions/
    └── [[path]].ts      # Catch-all function
キャッチオールハンドラー
// functions/[[path]].ts
import { Hono } from 'hono'
import { handle } from 'hono/cloudflare-pages'

const app = new Hono().basePath('/api')

app.get('/hello', (c) => c.json({ hello: 'world' }))
app.post('/echo', async (c) => c.json(await c.req.json()))

export const onRequest = handle(app)

バインディングを使ったミドルウェア

import { createMiddleware } from 'hono/factory'

type Bindings = {
  API_KEY: string
}

// Access env in middleware
const authMiddleware = createMiddleware<{ Bindings: Bindings }>(
  async (c, next) => {
    // Don't access env at module level - access in handler!
    const apiKey = c.req.header('X-API-Key')

    if (apiKey !== c.env.API_KEY) {
      return c.json({ error: 'Unauthorized' }, 401)
    }

    await next()
  }
)

app.use('/api/*', authMiddleware)

クイックリファレンス

バインディングの種類
type Bindings = {
  // Variables
  MY_VAR: string

  // KV
  MY_KV: KVNamespace

  // D1
  DB: D1Database

  // R2
  BUCKET: R2Bucket

  // Durable Objects
  MY_DO: DurableObjectNamespace

  // Queues
  MY_QUEUE: Queue

  // Service Bindings
  OTHER_WORKER: Fetcher
}
よく使うコマンド
# Local development
npx wrangler dev

# Deploy
npx wrangler deploy

# Create D1 database
npx wrangler d1 create my-database

# Execute D1 SQL
npx wrangler d1 execute my-database --file=schema.sql

# Create KV namespace
npx wrangler kv:namespace create MY_KV

# Create R2 bucket
npx wrangler r2 bucket create my-bucket

# Tail logs
npx wrangler tail

関連スキル

  • hono-core - フレームワークの基礎
  • hono-middleware - ミドルウェアのパターン
  • hono-testing - モックしたバインディングを使ったテスト

バージョン:Hono 4.x、Wrangler 3.x 最終更新:2025年1月 ライセンス:MIT

コメント