コンテンツへスキップ

アダプターヘルパー

アダプターヘルパーは、統一されたインターフェースを通じてさまざまなプラットフォームとシームレスにやり取りする方法を提供します。

インポート

ts
import { Hono } from 'hono'
import { env, getRuntimeKey } from 'hono/adapter'

env()

env()関数は、Cloudflare WorkersのBindingsだけでなく、異なるランタイム間で環境変数を取得しやすくします。env(c)で取得できる値は、ランタイムごとに異なる場合があります。

ts
import { env } from 'hono/adapter'

app.get('/env', (c) => {
  // NAME is process.env.NAME on Node.js or Bun
  // NAME is the value written in `wrangler.toml` on Cloudflare
  const { NAME } = env<{ NAME: string }>(c)
  return c.text(NAME)
})

サポートされているランタイム、サーバーレスプラットフォーム、およびクラウドサービス

ランタイムの指定

2番目の引数としてランタイムキーを渡すことで、環境変数を取得するランタイムを指定できます。

ts
app.get('/env', (c) => {
  const { NAME } = env<{ NAME: string }>(c, 'workerd')
  return c.text(NAME)
})

getRuntimeKey()

getRuntimeKey()関数は、現在のランタイムの識別子を返します。

ts
app.get('/', (c) => {
  if (getRuntimeKey() === 'workerd') {
    return c.text('You are on Cloudflare')
  } else if (getRuntimeKey() === 'bun') {
    return c.text('You are on Bun')
  }
  ...
})

利用可能なランタイムキー

以下は、利用可能なランタイムキーです。利用できないランタイムキーを持つランタイムは、otherとしてサポートおよびラベル付けされ、一部はWinterCGのランタイムキーに触発されています。

  • workerd - Cloudflare Workers
  • deno
  • bun
  • node
  • edge-light - Vercel Edge Functions
  • fastly - Fastly Compute
  • other - その他の不明なランタイムキー

MITライセンスの下でリリースされています。