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

  1. npm create hono@latest my-app

yarn

  1. yarn create hono my-app

pnpm

  1. pnpm create hono my-app

bun

  1. bun create hono@latest my-app

deno

  1. deno init --npm hono my-app

进入 my-app 目录并安装依赖。

npm

  1. cd my-app
  2. npm i

yarn

  1. cd my-app
  2. yarn

pnpm

  1. cd my-app
  2. pnpm i

bun

  1. cd my-app
  2. bun i

2. Hello World

如果你使用的是 App Router,编辑 app/api/[[...route]]/route.ts。更多选项可以参考 Supported HTTP Methods 章节。

  1. import { Hono } from 'hono'
  2. import { handle } from 'hono/vercel'
  3. export const runtime = 'edge'
  4. const app = new Hono().basePath('/api')
  5. app.get('/hello', (c) => {
  6. return c.json({
  7. message: 'Hello Next.js!',
  8. })
  9. })
  10. export const GET = handle(app)
  11. export const POST = handle(app)

如果你使用的是 Pages Router,编辑 pages/api/[[...route]].ts

  1. import { Hono } from 'hono'
  2. import { handle } from 'hono/vercel'
  3. import type { PageConfig } from 'next'
  4. export const config: PageConfig = {
  5. runtime: 'edge',
  6. }
  7. const app = new Hono().basePath('/api')
  8. app.get('/hello', (c) => {
  9. return c.json({
  10. message: 'Hello Next.js!',
  11. })
  12. })
  13. export default handle(app)

3. 运行

在本地运行开发服务器,然后在浏览器中访问 http://localhost:3000

npm

  1. npm run dev

yarn

  1. yarn dev

pnpm

  1. pnpm dev

bun

  1. bun run dev

此时 /api/hello 会返回 JSON。如果你构建了 React 界面,就可以用 Hono 创建一个完整的全栈应用。

4. 部署

如果你有 Vercel 账号,可以通过关联 Git 仓库进行部署。


Node.js

你也可以在运行于 Node.js 运行时的 Next.js 上运行 Hono。

App Router

对于 App Router,只需要在路由处理器中将运行时设置为 nodejs

  1. import { Hono } from 'hono'
  2. import { handle } from 'hono/vercel'
  3. export const runtime = 'nodejs'
  4. const app = new Hono().basePath('/api')
  5. app.get('/hello', (c) => {
  6. return c.json({
  7. message: 'Hello from Hono!',
  8. })
  9. })
  10. export const GET = handle(app)
  11. export const POST = handle(app)

Pages Router

对于 Pages Router,需要先安装 Node.js 适配器:

npm

  1. npm i @hono/node-server

yarn

  1. yarn add @hono/node-server

pnpm

  1. pnpm add @hono/node-server

bun

  1. bun add @hono/node-server

然后从 @hono/node-server/vercel 引入 handle 函数:

  1. import { Hono } from 'hono'
  2. import { handle } from '@hono/node-server/vercel'
  3. import type { PageConfig } from 'next'
  4. export const config: PageConfig = {
  5. api: {
  6. bodyParser: false,
  7. },
  8. }
  9. const app = new Hono().basePath('/api')
  10. app.get('/hello', (c) => {
  11. return c.json({
  12. message: 'Hello from Hono!',
  13. })
  14. })
  15. export default handle(app)

为了让 Pages Router 正常工作,需要在项目的控制面板或 .env 文件中关闭 Vercel 的 Node.js helpers:

  1. NODEJS_HELPERS=0