@fastify/auth

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

Run multiple auth functions in Fastify

原始使用文档
文档目录9 节
  1. Install
  2. Compatibility
  3. Usage
  4. Security Considerations
  5. Hook selection
  6. API
  7. Options
  8. Acknowledgments
  9. License

@fastify/auth

CI NPM version neostandard javascript style

This module does not provide an authentication strategy but offers a fast utility to handle authentication and multiple strategies in routes without adding overhead. See a complete example here.

Install

npm i @fastify/auth

Compatibility

Plugin versionFastify version
>=5.x^5.x
>=3.x <5.x^4.x
>=1.x <3.x^3.x
^0.x^2.x
^0.x^1.x

Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin in the table above. See Fastify's LTS policy for more details.

Usage

@fastify/auth does not provide an authentication strategy; authentication strategies must be provided using a decorator or another plugin.

The following example provides a straightforward implementation to demonstrate the usage of this module:

fastify
  .decorate('verifyJWTandLevel', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .decorate('verifyUserAndPassword', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .register(require('@fastify/auth'))
  .after(() => {
    fastify.route({
      method: 'POST',
      url: '/auth-multiple',
      preHandler: fastify.auth([
        fastify.verifyJWTandLevel,
        fastify.verifyUserAndPassword
      ]),
      handler: (req, reply) => {
        req.log.info('Auth route')
        reply.send({ hello: 'world' })
      }
    })
  })

The default relationship of these customized authentication strategies is or, but and can also be used:

fastify
  .decorate('verifyAdmin', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .decorate('verifyReputation', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .register(require('@fastify/auth'))
  .after(() => {
    fastify.route({
      method: 'POST',
      url: '/auth-multiple',
      preHandler: fastify.auth([
        fastify.verifyAdmin,
        fastify.verifyReputation
      ], {
        relation: 'and'
      }),
      handler: (req, reply) => {
        req.log.info('Auth route')
        reply.send({ hello: 'world' })
      }
    })
  })

For composite authentication, such as verifying user passwords and levels or meeting VIP criteria, use nested arrays. For example, the logic [(verifyUserPassword and verifyLevel) or (verifyVIP)] can be achieved with the following code:

fastify
  .decorate('verifyUserPassword', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .decorate('verifyLevel', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .decorate('verifyVIP', function (request, reply, done) {
    // your validation logic
    done() // pass an error if the authentication fails
  })
  .register(require('@fastify/auth'))
  .after(() => {
    fastify.route({
      method: 'POST',
      url: '/auth-multiple',
      preHandler: fastify.auth([
        [fastify.verifyUserPassword, fastify.verifyLevel], // The arrays within an array have the opposite relation to the main (default) relation.
        fastify.verifyVIP
      ], {
        relation: 'or' // default relation
      }),
      handler: (req, reply) => {
        req.log.info('Auth route')
        reply.send({ hello: 'world' })
      }
    })
  })

If the relation (defaultRelation) parameter is and, then the relation inside sub-arrays will be or. If the relation (defaultRelation) parameter is or, then the relation inside sub-arrays will be and.

auth coderesulting logical expression
fastify.auth([f1, f2, [f3, f4]], { relation: 'or' })f1 OR f2 OR (f3 AND f4)
fastify.auth([f1, f2, [f3, f4]], { relation: 'and' })f1 AND f2 AND (f3 OR f4)

The defaultRelation option can be used while registering the plugin to change the default relation:

fastify.register(require('@fastify/auth'), { defaultRelation: 'and'} )

For more examples, please check example-composited.js

This plugin supports callbacks and Promises returned by functions. Note that an async function does not have to call the done parameter, otherwise, the route handler linked to the auth methods might be called multiple times:

fastify
  .decorate('asyncVerifyJWTandLevel', async function (request, reply) {
    // your async validation logic
    await validation()
    // throws an error if the authentication fails
  })
  .decorate('asyncVerifyUserAndPassword', function (request, reply) {
    // return a promise that throws an error if the authentication fails
    return myPromiseValidation()
  })
  .register(require('@fastify/auth'))
  .after(() => {
    fastify.route({
      method: 'POST',
      url: '/auth-multiple',
      preHandler: fastify.auth([
        fastify.asyncVerifyJWTandLevel,
        fastify.asyncVerifyUserAndPassword
      ]),
      handler: (req, reply) => {
        req.log.info('Auth route')
        reply.send({ hello: 'world' })
      }
    })
  })

Route definition should be done as a plugin or within an .after() callback. For a complete example, see example.js.

@fastify/auth runs all authentication methods, allowing the request to continue if at least one succeeds; otherwise, it returns an error to the client. Any successful authentication stops @fastify/auth from trying the rest unless the run: 'all' parameter is provided:

fastify.route({
  method: 'GET',
  url: '/run-all',
  preHandler: fastify.auth([
    (request, reply, done) => { console.log('executed 1'); done() },
    (request, reply, done) => { console.log('executed 2'); done() },
    (request, reply, done) => { console.log('executed 3'); done(new Error('you are not authenticated')) },
    (request, reply, done) => { console.log('executed 4'); done() },
    (request, reply, done) => { console.log('executed 5'); done(new Error('you shall not pass')) }
  ], { run: 'all' }),
  handler: (req, reply) => { reply.send({ hello: 'world' }) }
})

This example shows all console logs and always replies with 401: you are not authenticated. The run parameter is useful for adding business data read from auth tokens to the request.

This plugin can be used at the route level as in the above example or at the hook level using the preHandler hook:

fastify.addHook('preHandler', fastify.auth([
  fastify.verifyJWTandLevel,
  fastify.verifyUserAndPassword
]))

fastify.route({
  method: 'POST',
  url: '/auth-multiple',
  handler: (req, reply) => {
    req.log.info('Auth route')
    reply.send({ hello: 'world' })
  }
})

The difference between the two approaches is that using the route-level preHandler function runs authentication for the selected route only, while using the preHandler hook runs authentication for all routes in the current plugin and its descendants.

Security Considerations

Hook selection

In the Fastify Lifecycle, the onRequest and preParsing stages do not parse the payload, unlike the preHandler stage. Parsing the body can be a potential security risk, as it can be used for denial of service (DoS) attacks. Therefore, it is recommended to avoid parsing the body for unauthorized access.

Using the @fastify/auth plugin in the preHandler hook can result in unnecessary memory allocation if a malicious user sends a large payload in the request body and the request is unauthorized. Fastify will parse the body, even though the request is not authorized, leading to unnecessary memory allocation. To avoid this, use an onRequest or preParsing hook for authentication if the method does not require the request body, such as @fastify/jwt, which expects authentication in the request header.

For authentication methods that require the request body, such as sending a token in the body, use the preHandler hook.

In mixed cases, you must use the preHandler hook.

API

Options

@fastify/auth accepts the options object:

{
  defaultRelation: 'and'
}
  • defaultRelation (Default: or): The default relation between the functions. It can be either or or and.

Acknowledgments

Past sponsors:

  • LetzDoIt

License

Licensed under MIT.

版本与发布记录

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

版本发布日期距今
5.1.2latest2026/10/091 个月前
5.1.12026/09/161 个月前
5.1.02026/08/083 个月前
5.0.42025/11/2811 个月前
5.0.32025/09/281.1 年前
5.0.22024/12/141.9 年前

其他发布通道:next → 5.0.0。

关于 @fastify/auth 的常见问题

@fastify/auth 是什么?

Run multiple auth functions in Fastify

如何安装 @fastify/auth?

在项目目录运行 npm install @fastify/auth,或使用 pnpm add / yarn add / bun add。

@fastify/auth 支持 TypeScript 吗?

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

@fastify/auth 支持 ESM 还是 CommonJS?

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

@fastify/auth 可以商用吗?

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

@fastify/auth 的下载量有多少?

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

@fastify/auth 还在维护吗?

最新版本 5.1.2 发布于 2026/10/09(1 个月前);至今共发布 22 个版本,其中过去 12 个月发布了 4 个;首次发布于 2022/04/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。