Skip to content

Next.js

Next.js 是一个灵活的 React 框架,提供构建快速 Web 应用所需的基础能力。

在使用 Node.js 运行时时,可以在 Next.js 中运行 Hono。 在 Vercel 上部署时,借助 Vercel Functions 可以轻松将 Hono 与 Next.js 结合。

1. 环境准备

Next.js 提供启动模板,可通过 create-hono 命令初始化项目。本示例选择 nextjs 模板。

sh
npm create hono@latest my-app
sh
yarn create hono my-app
sh
pnpm create hono my-app
sh
bun create hono@latest my-app
sh
deno init --npm hono my-app

进入 my-app 并安装依赖:

sh
cd my-app
npm i
sh
cd my-app
yarn
sh
cd my-app
pnpm i
sh
cd my-app
bun i

2. Hello World

如果使用 App Router,请编辑 app/api/[[...route]]/route.ts。更多支持的 HTTP 方法可参考官方文档

ts
import { Hono } from 'hono'
import { handle } from 'hono/vercel'

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)

3. 运行

启动本地开发服务器,并访问 http://localhost:3000

sh
npm run dev
sh
yarn dev
sh
pnpm dev
sh
bun run dev

此时 /api/hello 会返回 JSON。如果继续构建 React 界面,即可基于 Hono 构成完整的全栈应用。

4. 部署

若已拥有 Vercel 账号,可直接关联 Git 仓库进行部署。

Pages Router

若使用 Pages Router,需先安装 Node.js 适配器。

sh
npm i @hono/node-server
sh
yarn add @hono/node-server
sh
pnpm add @hono/node-server
sh
bun add @hono/node-server

然后在 pages/api/[[...route]].ts 中从 @hono/node-server/vercel 引入 handle

ts
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 Next.js!',
  })
})

export default handle(app)

在 Pages Router 中使用该方式时,需要禁用 Vercel Node.js helpers。请在项目控制台或 .env 中设置:

text
NODEJS_HELPERS=0

Released under the MIT License.