npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@fastify/basic-auth

v6.2.0

Published

Fastify Basic auth plugin

Readme

@fastify/basic-auth

CI NPM version neostandard javascript style

A simple Basic auth plugin for Fastify.

Install

npm i @fastify/basic-auth

Compatibility

| Plugin version | Fastify 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.