本文へ移動

アプリ - Hono ​

Hono は中心となるオブジェクトです。 最初にインポートし、アプリ全体を通して使用します。

ts
import { 
Hono
} from 'hono'
const
app
= new
Hono
()
//... export default
app
// for Cloudflare Workers or Bun

メソッド ​

Hono インスタンスには、以下のメソッドがあります。

  • app.HTTP_METHOD([path,]handler|middleware...)
  • app.all([path,]handler|middleware...)
  • app.on(method|method[], path|path[], handler|middleware...)
  • app.use([path,]middleware)
  • app.route(path, [app])
  • app.basePath(path)
  • app.notFound(handler)
  • app.onError(err, handler)
  • app.mount(path, anotherApp, [options])
  • app.fire()
  • app.fetch(request, env, event)
  • app.request(path, options)

冒頭のいくつかのメソッドはルーティングに使用します。ルーティングの章を参照してください。

リソースが見つからない場合 ​

app.notFound を使うと、リソースが見つからない場合のレスポンスをカスタマイズできます。

ts
app
.
notFound
((
c
) => {
return
c
.
text
('Custom 404 Message', 404)
})

注意

notFound メソッドは最上位のアプリからのみ呼び出されます。詳しくは、この issue を参照してください。

エラー処理 ​

app.onError を使うと、捕捉されなかったエラーを処理し、独自のレスポンスを返せます。

ts
app
.
onError
((
err
,
c
) => {
console
.
error
(`${
err
}`)
return
c
.
text
('Custom Error Message', 500)
})

情報

親アプリとそのルートの両方に onError ハンドラーがある場合、ルート側のハンドラーが優先されます。

fire() ​

注意

app.fire() は非推奨です。代わりに @hono/service-worker の fire() を使用してください。詳しくは Service Worker のドキュメントを参照してください。

app.fire() はグローバルな fetch イベントリスナーを自動的に追加します。

これは、ES モジュール形式ではない Cloudflare Workers など、Service Worker API に準拠する環境で役立ちます。

app.fire() は以下の処理を実行します。

ts
addEventListener('fetch', (event: FetchEventLike): void => {
  event.respondWith(this.dispatch(...))
})

fetch() ​

app.fetch がアプリケーションのエントリーポイントになります。

Cloudflare Workers では、以下のように記述できます。

ts
export default {
  
fetch
(
request
: Request,
env
:
Env
,
ctx
:
ExecutionContext
) {
return
app
.
fetch
(
request
,
env
,
ctx
)
}, }

または、次のように記述するだけでも構いません。

ts
export default 
app

Bun:

ts
export default app 
export default {  
  port: 3000, 
  fetch: app.fetch, 
} 

request() ​

request はテストに便利なメソッドです。

URL またはパス名を渡して GET リクエストを送信できます。 app は Response オブジェクトを返します。

ts
test
('GET /hello is ok', async () => {
const
res
= await
app
.
request
('/hello')
expect
(
res
.
status
).toBe(200)
})

Request オブジェクトを渡すこともできます。

ts
test
('POST /message is ok', async () => {
const
req
= new
Request
('Hello!', {
method
: 'POST',
}) const
res
= await
app
.
request
(
req
)
expect
(
res
.
status
).toBe(201)
})

mount() ​

注意

app.mount() は非推奨です。代わりに Mount ミドルウェアを使用してください。

mount() を使うと、ほかのフレームワークで構築したアプリケーションを Hono アプリにマウントできます。

ts
import { Router as IttyRouter } from 'itty-router'
import { Hono } from 'hono'

// Create itty-router application
const ittyRouter = IttyRouter()

// Handle `GET /itty-router/hello`
ittyRouter.get('/hello', () => new Response('Hello from itty-router'))

// Hono application
const app = new Hono()

// Mount!
app.mount('/itty-router', ittyRouter.handle)

デフォルトでは、mount() は URL からマウントパスを取り除いた新しい Request を渡します。replaceRequest 関数を指定すると、マウント先のアプリに渡す Request を制御できます。

ts
app
.
mount
('/app',
handler
, {
replaceRequest
: (
originalRequest
) =>
originalRequest
,
})

元の Request を変更せずに渡すには、上記の関数の省略形として replaceRequest を false に設定します。

ts
app
.
mount
('/app',
handler
, {
replaceRequest
: false,
})

厳密モード ​

厳密モードはデフォルトで true になっており、以下のルートを区別します。

  • /hello
  • /hello/

app.get('/hello') は GET /hello/ にマッチしません。

厳密モードを false に設定すると、両方のパスが同じものとして扱われます。

ts
const 
app
= new
Hono
({
strict
: false })

ルーターのオプション ​

router オプションは使用するルーターを指定します。デフォルトのルーターは SmartRouter です。RegExpRouter を使用する場合は、新しい Hono インスタンスに渡します。

ts
import { 
RegExpRouter
} from 'hono/router/reg-exp-router'
const
app
= new
Hono
({
router
: new
RegExpRouter
() })

ジェネリクス ​

ジェネリクスを渡すと、Cloudflare Workers の Bindings や、c.set/c.get で使用する変数の型を指定できます。

ts
type 
Bindings
= {
TOKEN
: string
} type
Variables
= {
user
:
User
} const
app
= new
Hono
<{
Bindings
:
Bindings
Variables
:
Variables
}>()
app
.
use
('/auth/*', async (
c
,
next
) => {
const
token
=
c
.
env
.
TOKEN
// token is `string`
// ...
c
.
set
('user',
user
) // user should be `User`
await
next
()
})

MIT ライセンスで公開されています。