Cloudflare Cloudflare

在 Cloudflare Workers 中运行您的 h3 应用程序

您可以使用 Web 适配器 直接将您的 h3 应用程序托管到 Cloudflare Workers

用法

创建应用条目:

app.mjs
js
import { createApp, defineEventHandler } from 'h3'

export const app = createApp()

app.use(defineEventHandler(() => 'Hello world!'))

为 Cloudflare Worker 创建条目:

cloudflare.mjs
js
import { toWebHandler } from 'h3'
import { app } from './app.mjs'

const handler = toWebHandler(app)

export default {
  async fetch(request, env, ctx) {
    return handler(request, {
      cloudflare: { env, ctx },
    })
  },
}

然后,创建一个简单的 wrangler.toml

wrangler.toml
ini
name = "h3-app"
main = "cloudflare.mjs"
compatibility_date = "2023-08-01"

最后,使用 wrangler dev 进行本地预览:

bash
npx wrangler dev

要部署,请使用wrangler deploy

bash
npx wrangler deploy

WebSocket 支持

ts
import wsAdapter from 'crossws/adapters/cloudflare'

const { handleUpgrade } = wsAdapter(app.websocket)

export default {
  async fetch(request, env, ctx) {
    if (request.headers.get('upgrade') === 'websocket') {
      return handleUpgrade(request, env, context)
    }
    return handler(request, {
      cloudflare: { env, ctx },
    })
  },
}

👉 查看 pi0/h3-on-edge 演示,获取完整工作示例 deployment