@fastify/nextjs

中文文档
11.0.1发布于 2026/10/09MITTypeScriptCommonJS构建来源已验证近 30 天下载 1.2万

React server side rendering support for Fastify with Next

原始使用文档
文档目录9 节
  1. Install
  2. Usage
  3. Assets serving
  4. under-pressure
  5. Custom properties on the request object
  6. Plugin Timeout and Next.js development mode
  7. Development
  8. Acknowledgements
  9. License

@fastify/nextjs

CI NPM version js-standard-style

React server-side rendering support for Fastify with Next.js framework. This library is for letting an existing Fastify server utilize NextJS, not for replacing NextJS' internal webserver with Fastify.

Install

npm i @fastify/nextjs next react react-dom

Usage

Since Next.js needs some time to be ready on the first launch, you must declare your routes inside the after callback, after you registered the plugin. The plugin will expose the next API in Fastify that will handle the rendering for you.

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')
})

All your server rendered pages must be saved in the folder pages, as you can see in the Next.js documentation.

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

If you need to pass custom options to next just pass them to register as second parameter.

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

If you need to handle the render part yourself, just pass a callback to next:

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

If you need to render with Next.js from within a custom handler, use reply.nextRender

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

If you need to render a Next.js error page, use reply.nextRenderError

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

If you need to handle HEAD routes, you can define the HTTP method:

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

Assets serving

By default plugin handle route ${basePath}/_next/* and forward to Next.js.

If you have custom preprocessing for _next/* requests, you can prevent this this handling with noServeAssets: true property for plugin options:

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()
      })
    })
  })

under-pressure

The plugin includes under-pressure, which can be configured by providing an underPressure property to the plugin options.

Using under-pressure allows implementing a circuit breaker that returns an error when the health metrics are not respected. Because React server side rendering is a blocking operation for the Node.js server, returning an error to the client allows signalling that the server is under too much load.

The available options are the same as those accepted by under-pressure.

For example:

fastify.register(require('@fastify/nextjs'), {
  underPressure: {
    exposeStatusRoute: true
  }
})
  • underPressure - bool|object

    • (default) when false, under-pressure is not registered
    • when true, under-pressure is registered with default options
    • when it is an object, under-pressure is registered with the provided options

Custom properties on the request object

If you want to share custom objects (for example other fastify plugin instances - e.g. @fastify/redis) across the server/client with each page request, you can use the onRequest hook to add it to the request object. Here is an example on how to do it:

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' })

In the example above we made the customProperty and redisInstance accessible in every request that is made to the server. On the client side it can be accessed like in this example:

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,
    }
  };
};

Plugin Timeout and Next.js development mode

The default timeout for plugins in Fastify is 10000ms, which can be a problem for huge Next.js Projects where the initial build time is higher than that. Usually, you will get an error like this:

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

The workaround or fix is to increase the plugin timeout:

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

Development

CI currently runs npm@6 so when upgrading packages, please use this version.

Acknowledgements

This project is kindly sponsored by:

Past sponsors:

  • LetzDoIt

License

Licensed under MIT.

版本与发布记录

@fastify/nextjs 共发布 11 个版本,首次发布于 2022/04/27;过去 12 个月发布了 1 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
11.0.1latest2026/10/091 个月前
11.0.02024/09/282 年前
10.0.12023/07/203 年前
10.0.02023/06/083 年前
9.2.02022/10/274 年前
9.1.12022/08/304 年前

关于 @fastify/nextjs 的常见问题

@fastify/nextjs 是什么?

React server side rendering support for Fastify with Next

如何安装 @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 和提交记录判断。