Skip to main content

Import

import { basicAuth } from 'hono/basic-auth'

Usage

const app = new Hono()

app.use(
  '/auth/*',
  basicAuth({
    username: 'hono',
    password: 'ahotproject',
  })
)

app.get('/auth/page', (c) => {
  return c.text('You are authorized')
})

Options

The basicAuth middleware accepts a BasicAuthOptions object:
username
string
The username for authentication. Required if verifyUser is not provided.
password
string
The password for authentication. Required if verifyUser is not provided.
verifyUser
(username: string, password: string, c: Context) => boolean | Promise<boolean>
Custom function to verify user credentials. Alternative to providing username and password.
realm
string
default:"Secure Area"
The realm attribute for the WWW-Authenticate header.
hashFunction
Function
The hash function used for secure comparison of credentials.
invalidUserMessage
string | object | MessageFunction
default:"Unauthorized"
The message returned when authentication fails. Can be a string, object, or function that returns either.
onAuthSuccess
(c: Context, username: string) => void | Promise<void>
Callback function called on successful authentication. Useful for setting user context.

Signature

basicAuth(
  options: BasicAuthOptions,
  ...users: { username: string; password: string }[]
): MiddlewareHandler

Examples

With onAuthSuccess callback

app.use(
  '/auth/*',
  basicAuth({
    username: 'hono',
    password: 'ahotproject',
    onAuthSuccess: (c, username) => {
      c.set('user', { name: username, role: 'admin' })
      console.log(`User ${username} authenticated`)
    },
  })
)

With custom verifyUser function

app.use(
  '/auth/*',
  basicAuth({
    verifyUser: async (username, password, c) => {
      // Check credentials against database
      const user = await db.users.findOne({ username })
      return user && await comparePassword(password, user.hashedPassword)
    },
  })
)

Multiple users

app.use(
  '/auth/*',
  basicAuth(
    { username: 'admin', password: 'secret1' },
    { username: 'user', password: 'secret2' }
  )
)

Behavior

  • Returns 401 Unauthorized if credentials are missing or invalid
  • Sets WWW-Authenticate header with the specified realm
  • Uses timing-safe comparison to prevent timing attacks
  • Supports custom hash functions for secure credential comparison
  • Can validate multiple username/password pairs

Build docs developers (and LLMs) love