Vercel
Vercel はフロントエンド開発者のためのプラットフォームで、イノベーターがインスピレーションの瞬間に制作をするために必要なスピードと信頼性を提供します。 このセクションでは Vercel 上で実行される Next.js 紹介します。
Next.js は、高速な Web アプリケーションを作成するための要素を提供する柔軟な React フレームワークです。
Next.js では Edge Functions を使用して Vercel などのエッジランタイムに動的 API を作成できます。 Hono を使用すると、他のランタイムと同じ構文で API を記述し、多くのミドルウェアが使用できます。
1. セットアップ
Next.js 向けのスターターもあります。 "create-hono" コマンドで始めましょう。 nextjs
テンプレートを選択します。
npm create hono@latest my-app
yarn create hono my-app
pnpm create hono my-app
bun create hono@latest my-app
deno init --npm hono my-app
my-app
に移動し、依存関係をインストールします。
cd my-app
npm i
cd my-app
yarn
cd my-app
pnpm i
cd my-app
bun i
2. Hello World
App Router を使用している場合 app/api/[[...route]]/route.ts
に書いてください。 Supported HTTP Methods も参照してください。
import { Hono } from 'hono'
import { handle } from 'hono/vercel'
export const runtime = 'edge'
const app = new Hono().basePath('/api')
app.get('/hello', (c) => {
return c.json({
message: 'Hello Next.js!',
})
})
export const GET = handle(app)
export const POST = handle(app)
Pages Router を使用している場合は pages/api/[[...route]].ts
に記述します。
import { Hono } from 'hono'
import { handle } from 'hono/vercel'
import type { PageConfig } from 'next'
export const config: PageConfig = {
runtime: 'edge',
}
const app = new Hono().basePath('/api')
app.get('/hello', (c) => {
return c.json({
message: 'Hello Next.js!',
})
})
export default handle(app)
3. Run
開発サーバーをローカルで動かし、ブラウザで http://localhost:3000
にアクセスしましょう。
npm run dev
yarn dev
pnpm dev
bun run dev
今は /api/hello
で JSON を返すだけですが、 React で UI を作成すれば Hono でフルスタックアプリケーションを作成できます。
4. デプロイ
Vercel アカウントを持っている場合は Git 連携でデプロイ出来ます。
Node.js
Node.js ランタイム上の Next.js で Hono を使うことも出来ます。
App Router
App Router では、ルートハンドラのランタイムを nodejs
に設定するだけで使用できます:
import { Hono } from 'hono'
import { handle } from 'hono/vercel'
export const runtime = 'nodejs'
const app = new Hono().basePath('/api')
app.get('/hello', (c) => {
return c.json({
message: 'Hello from Hono!',
})
})
export const GET = handle(app)
export const POST = handle(app)
Pages Router
Pages Router では、まず Node.js アダプタをインストールする必要があります:
npm i @hono/node-server
yarn add @hono/node-server
pnpm add @hono/node-server
bun add @hono/node-server
次に、 @hono/node-server/vercel
からインポートした handle
を使用します:
import { Hono } from 'hono'
import { handle } from '@hono/node-server/vercel'
import type { PageConfig } from 'next'
export const config: PageConfig = {
api: {
bodyParser: false,
},
}
const app = new Hono().basePath('/api')
app.get('/hello', (c) => {
return c.json({
message: 'Hello from Hono!',
})
})
export default handle(app)
これを Pages Router で動かすためには、プロジェクトダッシュボードか .env
ファイルで環境変数を設定して Vercel の Node.js ヘルパーを無効化することが重要です:
NODEJS_HELPERS=0