Vercel
Vercel 是一个面向前端开发者的平台,提供创新者在灵感迸发时所需的速度和可靠性。本节介绍在 Vercel 上运行的 Next.js。
Next.js 是一个灵活的 React 框架,它为你提供了构建快速 Web 应用的基础模块。
在 Next.js 中,Edge Functions 允许你在 Edge Runtime(如 Vercel)上创建动态 API。借助 Hono,你可以用和其他运行时相同的语法编写 API,并使用丰富的中间件。
1. 设置
Next.js 提供了一个快速启动模板。你可以通过 create-hono
命令启动项目。本示例选择 nextjs
模板。
npm
npm create hono@latest my-app
yarn
yarn create hono my-app
pnpm
pnpm create hono my-app
bun
bun create hono@latest my-app
deno
deno init --npm hono my-app
进入 my-app
目录并安装依赖。
npm
cd my-app
npm i
yarn
cd my-app
yarn
pnpm
cd my-app
pnpm i
bun
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. 运行
在本地运行开发服务器,然后在浏览器中访问 http://localhost:3000
。
npm
npm run dev
yarn
yarn dev
pnpm
pnpm dev
bun
bun run dev
此时 /api/hello
会返回 JSON。如果你构建了 React 界面,就可以用 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
npm i @hono/node-server
yarn
yarn add @hono/node-server
pnpm
pnpm add @hono/node-server
bun
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 helpers:
NODEJS_HELPERS=0