Vercel
Vercel 是前端开发者的平台,提供创新者在灵感迸发时所需的的速度和可靠性。本节介绍在 Vercel 上运行的 Next.js。
Next.js 是一个灵活的 React 框架,它为你提供了构建快速 Web 应用程序的构建模块。
在 Next.js 中,Edge Functions 允许你在 Edge Runtime (例如 Vercel) 上创建动态 API。 借助 Hono,你可以使用与其他运行时相同的语法编写 API,并使用许多中间件(middleware)。
1. Setup
Next.js 的启动器(starter)已经可用。 使用 "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
在本地运行开发服务器。然后,在你的 Web 浏览器中访问 http://localhost:3000
。
npm run dev
yarn dev
pnpm dev
bun run dev
现在,/api/hello
仅返回 JSON,但是如果你构建 React UI,你可以使用 Hono 创建一个全栈应用程序。
4. Deploy
如果你有 Vercel 帐户,则可以通过链接 Git 仓库来部署。
Node.js
你也可以在运行于 Node.js runtime 的 Next.js 上运行 Hono。
App Router
对于 App Router,你可以简单地在你的路由处理程序中将 runtime 设置为 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!', // 来自 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!', // 来自 Hono 的问候!
})
})
export default handle(app)
为了使其与 Pages Router 一起工作,重要的是通过在你的项目仪表板或你的 .env
文件中设置环境变量来禁用 Vercel Node.js 助手:
NODEJS_HELPERS=0