Skip to content

bearerAuth

reference
1 min readUpdated

Kind: Function

Source: src/middleware/bearer-auth/index.ts

Part of: Middleware

Bearer Auth Middleware for Hono.

bearerAuth is Hono middleware that validates the Bearer token from an incoming request’s Authorization header. Apply it to routes or an app to reject requests with missing or invalid tokens before the route handler runs.

Signature

ts
function bearerAuth(options: BearerAuthOptions<E>): MiddlewareHandler<E>

Parameters

NameType
optionsBearerAuthOptions<E>

Returns: MiddlewareHandler<E>

Diagram

mermaid
graph LR
  Request[Incoming request] --> Middleware[bearerAuth middleware]
  Middleware --> Header[Authorization header]
  Header --> Token[Bearer token validation]
  Token -->|Valid| Handler[Route handler]
  Token -->|Missing or invalid| Unauthorized[Unauthorized response]

Usage

ts
import { Hono } from 'hono'
import { bearerAuth } from 'hono/bearer-auth'

const app = new Hono()

app.use(
  '/api/*',
  bearerAuth({
    token: 'my-secret-token',
  })
)

app.get('/api/profile', (c) => {
  return c.json({ message: 'Authenticated request' })
})

export default app

AI Coding Instructions

  • Apply bearerAuth before handlers that require authenticated requests.
  • Pass the expected token with the token option, or provide token verification logic when authentication rules need custom validation.
  • Send credentials through the Authorization: Bearer <token> request header.
  • Scope middleware to protected route prefixes when public routes must remain accessible.

Relationships

  • IMPORTS → HTTPException
  • IMPORTS → timingSafeEqual

Was this page helpful?

Download as PDF
bearerAuth — Hono (narrator proof)