@fastify/basic-auth

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

Fastify Basic auth plugin

原始使用文档
文档目录12 节
  1. Install
  2. Compatibility
  3. Usage
  4. Custom error handler
  5. Options
  6. utf8 (optional, default: true)
  7. strictCredentials (optional, default: true)
  8. validate (required)
  9. authenticate <Boolean|Object> (optional, default: false)
  10. proxyMode Boolean (optional, default: false)
  11. header String (optional)
  12. License

@fastify/basic-auth

CI NPM version neostandard javascript style

A simple Basic auth plugin for Fastify.

Install

npm i @fastify/basic-auth

Compatibility

Plugin versionFastify version
>=6.x^5.x
^4.x^4.x
>=1.x <4.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

This plugin decorates the fastify instance with a basicAuth function, which can be used inside any hook before a route handler, or with @fastify/auth.

const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
// `this` inside validate is `fastify`
function validate (username, password, req, reply, done) {
  if (username === 'Tyrion' && password === 'wine') {
    done()
  } else {
    done(new Error('Winter is coming'))
  }
}

fastify.after(() => {
  fastify.addHook('onRequest', fastify.basicAuth)

  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })
})

Promises and async/await are supported as well!

const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
  if (username !== 'Tyrion' || password !== 'wine') {
    return new Error('Winter is coming')
  }
}

Use with onRequest:

const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
  if (username !== 'Tyrion' || password !== 'wine') {
    return new Error('Winter is coming')
  }
}

fastify.after(() => {
  fastify.route({
    method: 'GET',
    url: '/',
    onRequest: fastify.basicAuth,
    handler: async (req, reply) => {
      return { hello: 'world' }
    }
  })
})

Use with @fastify/auth:

const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/auth'))
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
  if (username !== 'Tyrion' || password !== 'wine') {
    return new Error('Winter is coming')
  }
}

fastify.after(() => {
  // use preHandler to authenticate all the routes
  fastify.addHook('preHandler', fastify.auth([fastify.basicAuth]))

  fastify.route({
    method: 'GET',
    url: '/',
    // use onRequest to authenticate just this one
    onRequest: fastify.auth([fastify.basicAuth]),
    handler: async (req, reply) => {
      return { hello: 'world' }
    }
  })
})

Custom error handler

On failed authentication, @fastify/basic-auth calls the Fastify generic error handler with an error and sets err.statusCode to 401.

To properly 401 errors:

fastify.setErrorHandler(function (err, req, reply) {
  if (err.statusCode === 401) {
    // This was unauthorized! Display the correct page/message
    reply.code(401).send({ was: 'unauthorized' })
    return
  }
  reply.send(err)
})

Options

utf8 (optional, default: true)

User-ids or passwords with non-US-ASCII characters may cause issues unless both parties agree on the encoding scheme. Setting utf8 to true sends the 'charset' parameter to prefer "UTF-8", increasing the likelihood that clients will use that encoding.

strictCredentials (optional, default: true)

Setting strictCredentials to false allows additional whitespaces at the beginning, middle, and end of the authorization header. This is a fallback option to ensure the same behavior as @fastify/basic-auth version <=5.x.

validate (required)

The validate function is called on each request made and is passed the username, password, req, and reply parameters, in that order. An optional fifth parameter, done, can be used to signify a valid request when called with no arguments or an invalid request when called with an Error object. Alternatively, the validate function can return a promise, resolving for valid requests and rejecting for invalid. This can also be achieved using an async/await function, and throwing for invalid requests.

See code above for examples.

authenticate <Boolean|Object> (optional, default: false)

The authenticate option adds the WWW-Authenticate header and can set the realm value.

This can trigger client-side authentication interfaces, such as the browser authentication dialog.

Setting authenticate to true adds the header WWW-Authenticate: Basic. When false, no header is added (default).

When proxyMode is true it will use the Proxy-Authenticate header instead.

fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: true // WWW-Authenticate: Basic
})

fastify.register(require('@fastify/basic-auth'), {
  validate,
  proxyMode: true,
  authenticate: true // Proxy-Authenticate: Basic
})

fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: false // no authenticate header, same as omitting authenticate option
})

The authenticate option can have a realm key when supplied as an object. If the realm key is supplied, it will be appended to the header value:

fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: {realm: 'example'} // WWW-Authenticate: Basic realm="example"
})

The realm key can also be a function:

fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: {
    realm(req) {
      return 'example' // WWW-Authenticate: Basic realm="example"
    }
  }
})

The authenticate object can include an optional header key to customize the header name, replacing the default WWW-Authenticate:

fastify.register(require('@fastify/basic-auth'), {
  validate,
  authenticate: {
    header: 'Proxy-Authenticate' // Proxy-Authenticate: Basic
  }
})

proxyMode Boolean (optional, default: false)

Setting the proxyMode to true will make the plugin implement HTTP proxy authentication, rather than resource authentication. In other words, the plugin will:

  • read credentials from the Proxy-Authorization header rather than Authorization
  • use 407 response status code instead of 401 to signal missing or invalid credentials
  • use the Proxy-Authenticate header rather than WWW-Authenticate if the authenticate option is set

header String (optional)

The header option specifies the header name to get credentials from for validation. If not specified it defaults to Authorization or Proxy-Authorization (according to the value of proxyMode option)

fastify.register(require('@fastify/basic-auth'), {
  validate,
  header: 'x-forwarded-authorization'
})

License

Licensed under MIT.

版本与发布记录

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

版本发布日期距今
6.3.1latest2026/10/091 个月前
6.3.02026/08/083 个月前
6.2.02025/04/251.6 年前
6.1.02025/04/141.6 年前
6.0.32025/01/021.9 年前
6.0.22024/12/141.9 年前

其他发布通道:next → 6.0.0。

关于 @fastify/basic-auth 的常见问题

@fastify/basic-auth 是什么?

Fastify Basic auth plugin

如何安装 @fastify/basic-auth?

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

@fastify/basic-auth 支持 TypeScript 吗?

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

@fastify/basic-auth 支持 ESM 还是 CommonJS?

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

@fastify/basic-auth 可以商用吗?

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

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

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

@fastify/basic-auth 还在维护吗?

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