Cloudflare Pages
Cloudflare Pagesは、フルスタックWebアプリケーションのためのエッジプラットフォームです。静的ファイルと、Cloudflare Workersによって提供される動的コンテンツを提供します。
HonoはCloudflare Pagesを完全にサポートしています。これにより、快適な開発者体験がもたらされます。Viteの開発サーバーは高速で、Wranglerを使用したデプロイは非常に迅速です。
1. セットアップ
Cloudflare Pagesのスターターが利用可能です。「create-hono」コマンドでプロジェクトを開始してください。この例では、cloudflare-pages
テンプレートを選択してください。
npm create hono@latest my-app
yarn create hono my-app
pnpm create hono my-app
bunx create-hono my-app
deno run -A npm:create-hono my-app
my-app
に移動し、依存関係をインストールします。
cd my-app
npm i
cd my-app
yarn
cd my-app
pnpm i
cd my-app
bun i
以下は基本的なディレクトリ構造です。
./
├── package.json
├── public
│ └── static // Put your static files.
│ └── style.css // You can refer to it as `/static/style.css`.
├── src
│ ├── index.tsx // The entry point for server-side.
│ └── renderer.tsx
├── tsconfig.json
└── vite.config.ts
2. Hello World
src/index.tsx
を以下のように編集します
import { Hono } from 'hono'
import { renderer } from './renderer'
const app = new Hono()
app.get('*', renderer)
app.get('/', (c) => {
return c.render(<h1>Hello, Cloudflare Pages!</h1>)
})
export default app
3. 実行
ローカルで開発サーバーを実行します。次に、Webブラウザでhttp://localhost:5173
にアクセスします。
npm run dev
yarn dev
pnpm dev
bun run dev
4. デプロイ
Cloudflareアカウントをお持ちの場合は、Cloudflareにデプロイできます。package.json
で、$npm_execpath
を任意のパッケージマネージャーに変更する必要があります。
npm run deploy
yarn deploy
pnpm run deploy
bun run deploy
GitHubを使用してCloudflareダッシュボード経由でデプロイ
- Cloudflareダッシュボードにログインし、アカウントを選択します。
- アカウントホームで、Workers & Pages > アプリケーションの作成 > Pages > Gitに接続 を選択します。
- GitHubアカウントを認証し、リポジトリを選択します。ビルドとデプロイの設定で、以下の情報を提供します。
設定オプション | 値 |
---|---|
本番ブランチ | main |
ビルドコマンド | npm run build |
ビルドディレクトリ | dist |
バインディング
変数、KV、D1などのCloudflareバインディングを使用できます。このセクションでは、変数とKVを使用してみましょう。
wrangler.toml
を作成
最初に、ローカルバインディング用のwrangler.toml
を作成します
touch wrangler.toml
wrangler.toml
を編集します。MY_NAME
という名前の変数を指定します。
[vars]
MY_NAME = "Hono"
KVを作成
次に、KVを作成します。次のwrangler
コマンドを実行します
wrangler kv namespace create MY_KV --preview
次の出力として、preview_id
をメモします。
{ binding = "MY_KV", preview_id = "abcdef" }
preview_id
をバインディングの名前MY_KV
で指定します
[[kv_namespaces]]
binding = "MY_KV"
id = "abcdef"
vite.config.ts
を編集
vite.config.ts
を編集します
import devServer from '@hono/vite-dev-server'
import adapter from '@hono/vite-dev-server/cloudflare'
import build from '@hono/vite-cloudflare-pages'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
devServer({
entry: 'src/index.tsx',
adapter, // Cloudflare Adapter
}),
build(),
],
})
アプリケーションでバインディングを使用
アプリケーションで変数とKVを使用します。型を設定します。
type Bindings = {
MY_NAME: string
MY_KV: KVNamespace
}
const app = new Hono<{ Bindings: Bindings }>()
それらを使用します
app.get('/', async (c) => {
await c.env.MY_KV.put('name', c.env.MY_NAME)
const name = await c.env.MY_KV.get('name')
return c.render(<h1>Hello! {name}</h1>)
})
本番環境では
Cloudflare Pagesでは、ローカル開発にはwrangler.toml
を使用しますが、本番環境ではダッシュボードでバインディングを設定します。
クライアント側
Viteの機能を使用して、クライアント側のスクリプトを作成し、アプリケーションにインポートできます。/src/client.ts
がクライアントのエントリーポイントの場合、スクリプトタグに記述するだけです。さらに、import.meta.env.PROD
は、開発サーバーで実行しているか、ビルドフェーズで実行しているかを検出するのに役立ちます。
app.get('/', (c) => {
return c.html(
<html>
<head>
{import.meta.env.PROD ? (
<script type='module' src='/static/client.js'></script>
) : (
<script type='module' src='/src/client.ts'></script>
)}
</head>
<body>
<h1>Hello</h1>
</body>
</html>
)
})
スクリプトを適切にビルドするには、以下に示す例の構成ファイルvite.config.ts
を使用できます。
import pages from '@hono/vite-cloudflare-pages'
import devServer from '@hono/vite-dev-server'
import { defineConfig } from 'vite'
export default defineConfig(({ mode }) => {
if (mode === 'client') {
return {
build: {
rollupOptions: {
input: './src/client.ts',
output: {
entryFileNames: 'static/client.js',
},
},
},
}
} else {
return {
plugins: [
pages(),
devServer({
entry: 'src/index.tsx',
}),
],
}
}
})
次のコマンドを実行して、サーバーとクライアントのスクリプトをビルドできます。
vite build --mode client && vite build
Cloudflare Pagesミドルウェア
Cloudflare Pagesは、Honoのミドルウェアとは異なる独自のミドルウェアシステムを使用します。_middleware.ts
という名前のファイルでonRequest
をエクスポートすることで有効にできます。次のようになります。
// functions/_middleware.ts
export async function onRequest(pagesContext) {
console.log(`You are accessing ${pagesContext.request.url}`)
return await pagesContext.next()
}
handleMiddleware
を使用すると、HonoのミドルウェアをCloudflare Pagesミドルウェアとして使用できます。
// functions/_middleware.ts
import { handleMiddleware } from 'hono/cloudflare-pages'
export const onRequest = handleMiddleware(async (c, next) => {
console.log(`You are accessing ${c.req.url}`)
await next()
})
また、Honoの組み込みおよびサードパーティ製のミドルウェアも使用できます。たとえば、ベーシック認証を追加するには、Honoのベーシック認証ミドルウェアを使用できます。
// functions/_middleware.ts
import { handleMiddleware } from 'hono/cloudflare-pages'
import { basicAuth } from 'hono/basic-auth'
export const onRequest = handleMiddleware(
basicAuth({
username: 'hono',
password: 'acoolproject',
})
)
複数のミドルウェアを適用する場合は、次のように記述できます。
import { handleMiddleware } from 'hono/cloudflare-pages'
// ...
export const onRequest = [
handleMiddleware(middleware1),
handleMiddleware(middleware2),
handleMiddleware(middleware3),
]
EventContext
へのアクセス
EventContext
オブジェクトには、handleMiddleware
のc.env
を介してアクセスできます。
// functions/_middleware.ts
import { handleMiddleware } from 'hono/cloudflare-pages'
export const onRequest = [
handleMiddleware(async (c, next) => {
c.env.eventContext.data.user = 'Joe'
await next()
}),
]
次に、ハンドラー内のc.env.eventContext
を介してデータ値にアクセスできます。
// functions/api/[[route]].ts
import type { EventContext } from 'hono/cloudflare-pages'
import { handle } from 'hono/cloudflare-pages'
// ...
type Env = {
Bindings: {
eventContext: EventContext
}
}
const app = new Hono<Env>()
app.get('/hello', (c) => {
return c.json({
message: `Hello, ${c.env.eventContext.data.user}!`, // 'Joe'
})
})
export const onRequest = handle(app)