# @fastify/nextjs 中文文档

规范地址：https://npmcn.com/package/%40fastify/nextjs/

版本：11\.0\.1
npm 元数据更新时间：2026-10-18T12:30:53.985Z
中文译文更新时间：2026-11-14T11:26:51.980Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40fastify/nextjs
原文对照：https://npmcn.com/package/%40fastify/nextjs/?lang=original
项目主页：https://github.com/fastify/fastify-nextjs#readme
源码仓库：https://github.com/fastify/fastify-nextjs

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：36.2 kB，18 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：next 12\.x\.x \|\| 13\.x\.x
- 首次发布：2022-04-27T14:02:11.242Z
- 最新版本发布：2026-10-09T15:42:41.122Z
- 近 30 天下载量：11616（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：11（近 12 个月 1 个）

## 中文简介

响应服务器侧面为 Next Fastify 提供支持

## 安装

```sh
npm install @fastify/nextjs
```

也可以使用：`pnpm add @fastify/nextjs`、`yarn add @fastify/nextjs`、`bun add @fastify/nextjs`

## README

# @ fastify/ nextjs (英语)

[![CI](https://github.com/fastify/fastify-nextjs/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-nextjs/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/nextjs.svg?style=flat)](https://www.npmjs.com/package/@fastify/nextjs) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)

反应服务器侧渲染支持 [下一个.js](https://nextjs.org/docs/advanced-features/custom-server) 框架。 这个库是用来让一个已存在的Fastify服务器使用NextJS,而不是用来用Fastify替换NextJS的内部网络服务器.

## 安装

```
npm i @fastify/nextjs next react react-dom
```

## 使用量

由于Next.js在第一次发射时需要一些时间准备,你必须宣布你的路线 `after` 在您注册了插件后调用 . 插件将曝光 `next` API in Fastify 可以帮你处理渲染.

```js
const fastify = require('fastify')()

fastify
  .register(require('@fastify/nextjs'))
  .after(() => {
    fastify.next('/hello')
  })

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log('Server listening on http://localhost:3000')
})
```

您的服务器提供的所有页面必须保存在文件夹中 `pages`,正如你可以看到 [Next.js 文档](https://nextjs.org/docs/advanced-features/custom-server)。 。 。 .

```js
// /pages/hello.js
export default () => <div>hello world</div>
```

如果你需要通过 [自定义选项](https://nextjs.org/docs/advanced-features/custom-server) 改为 `next` 只要通过它们注册为第二个参数.

```js
fastify.register(require('@fastify/nextjs'), { dev: true })
```

如果你需要自己处理部分 只需回电给 `next`数字 :

```js
fastify.next('/hello', (app, req, reply) => {
  // your code
  // `app` is the Next instance
  app.render(req.raw, reply.raw, '/hello', req.query, {})
})
```

如果您需要从自定义处理器内切入 Next.js, 请使用 `reply.nextRender`

```js
app.setErrorHandler((err, req, reply) => {
  return reply.nextRender('/a')
})
```

如果您需要制作 Next.js 错误页面,请使用 `reply.nextRenderError`

```js
app.setErrorHandler((err, req, reply) => {
  return reply.status(err.statusCode || 500).nextRenderError(err)
})
```

如果您需要处理 Head 路由, 您可以定义 HTTP 方法 :

```js
fastify.next('/api/*', { method: 'GET' });
fastify.next('/api/*', { method: 'HEAD' });
```

### 服务资产

默认的插件处理路由 `${basePath}/_next/*` 并转至Next.js.

如果您有自定义预处理 `_next/*` 请求中,您可以防止此处理 `noServeAssets: true` 插件选项的属性 :

```js
fastify
  .register(require('@fastify/nextjs'), {
    noServeAssets: true
  })
  .after(() => {
    fastify.next(`${process.env.BASE_PATH || ''}/_next/*`, (app, req, reply) => {
      // your code
      app.getRequestHandler()(req.raw, reply.raw).then(() => {
        reply.hijack()
      })
    })
  })
```

### 压低

插件包含 [压低](https://github.com/fastify/under-pressure),可以通过提供 `underPressure` 属性到插件选项.

使用 `under-pressure` 允许执行一个断路器,在健康指标没有得到遵守时返回出错. 因为React服务器侧渲染是针对Node.js服务器的屏蔽操作,向客户端还原出一个错误,允许信号显示服务器负荷过大.

现有备选方案与接受的备选方案相同 `under-pressure`。 。 。 .

例如:

```js
fastify.register(require('@fastify/nextjs'), {
  underPressure: {
    exposeStatusRoute: true
  }
})
```

-   `underPressure` - 说吧 `bool|object`
    
    -   当虚伪的时候, `under-pressure` 未注册
    -   当真理降临的时候, `under-pressure` 以默认选项注册
    -   当它是一个物体的时候, `under-pressure` 以提供的选项注册

## 在请求对象上自定义属性

如果您想共享自定义对象( 例如其它自定义插件实例 - 例如, @ fastify/redis) , 您可以在服务器/ 客户端之间与每个页面请求共享, 请使用 `onRequest` 钩子将其添加到请求对象中. 以下是如何做到这一点的例子:

```js
const Fastify = require('fastify')
const FastifyRedis = require('@fastify/redis')
const FastifyNextJS = require('@fastify/nextjs')

const fastify = Fastify()
fastify.register(FastifyRedis, { host: '127.0.0.1' })
fastify.register(FastifyNextJS)

fastify.register(function(instance) {
  // for performance reasons we do not want it to run on every request
  // only the nextjs one should run
  instance.addHook('onRequest', function(request, reply, done) {
    // define a custom property on the request
    request.raw.customProperty = { hello: "world" }
    // OR make the instance of @fastify/redis available in the request
    request.raw.redisInstance = instance.redis
    done()
  })

  instance.next('/', function(app, request, reply) {
    // your custom property containing the object will be available here
    // request.raw.customProperty
    // OR the redis instance
    // request.raw.redisInstance
    app.render(request.raw, reply.raw, '/hello', request.query, {})
  })
}, { prefix: '/hello' })
```

在上述例子中,我们创造了 `customProperty` 财务报告和审定财务报表 `redisInstance` 可以在向服务器提出的每个请求中访问。 在客户端,可以像这个例子一样访问:

```js
const CustomPropPage = ({ cp, ri }) => <div>custom property value: {cp} | redis instance: {ri}</div>;

export default CustomPropPage;

export const getServerSideProps = async function (ctx) {
  return {
    props: {
      cp: ctx.req.customProperty,
      ri: ctx.req.redisInstance,
    }
  };
};
```

## 插件超时和 Next.js 开发模式

Fastify中插件的默认超时为1000ms,这对巨大的Next.js Projects来说可能是一个问题,因为其初始建设时间高于此. 通常,你会遇到这样的错误:

```
Error: ERR_AVVIO_PLUGIN_TIMEOUT: plugin did not start in time: /app/node_modules/@fastify/nextjs/index.js. You may have forgotten to call 'done' function or to resolve a Promise
```

工作或固定是增加插件超时 :

```js
const isDev = process.env.NODE_ENV !== 'production';
const fastify = Fastify({ pluginTimeout: isDev ? 120_000 : undefined });
```

## 发展

CI目前运行npm@6,所以在升级软件包时,请使用这个版本.

## 鸣谢

这个项目由下列各方慷慨赞助:

-   [临近论坛](https://nearform.com/)

过去提案国:

-   莱兹

## 许可证

许可证根据 [麻省理工学院](https://npmcn.com/package/%40fastify/nextjs/LICENSE)。 。 。 .

## 常见问题

### @fastify/nextjs 是什么？

响应服务器侧面为 Next Fastify 提供支持

### 如何安装 @fastify/nextjs？

在项目目录运行 npm install @fastify/nextjs，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：next（12\.x\.x \|\| 13\.x\.x）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @fastify/nextjs 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @fastify/nextjs 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @fastify/nextjs 可以商用吗？

@fastify/nextjs 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @fastify/nextjs 的下载量有多少？

根据 npm 官方下载统计，@fastify/nextjs 在 2026/10/15 – 2026/11/13 这 30 天内被下载 11,616 次，日均约 387 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @fastify/nextjs 还在维护吗？

最新版本 11\.0\.1 发布于 2026/10/09（1 个月前）；至今共发布 11 个版本，其中过去 12 个月发布了 1 个；首次发布于 2022/04/27。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

