Getting Started
Core Concepts
Built-In Middleware
Advanced Features
Troubleshooting
Authentication and security are critical components of any web application. This library provides built-in middleware to handle standard authentication patterns and protect your application against common web vulnerabilities, including Cross-Site Request Forgery (CSRF) and Cross-Origin Resource Sharing (CORS) issues.
You can secure your routes using either Basic Auth or Bearer Token authentication.
Used for protecting routes using standard username and password credentials.
import { Hono } from 'hono'
import { basicAuth } from 'hono/basic-auth'
const app = new Hono()
app.use(
'/admin/*',
basicAuth({
username: 'admin',
password: 'password123',
})
)Used for token-based authentication, typically for API endpoints.
import { Hono } from 'hono'
import { bearerAuth } from 'hono/bearer-auth'
const app = new Hono()
app.use('/api/*', bearerAuth({ token: 'my-secret-token' }))These tools protect your application from malicious cross-origin requests.
Allows you to control which domains are permitted to access your resources.
import { Hono } from 'hono'
import { cors } from 'hono/cors'
const app = new Hono()
app.use('/api/*', cors({
origin: 'https://example.com',
allowMethods: ['GET', 'POST'],
}))Protects against attacks where a malicious site tricks a user's browser into performing unwanted actions on your application.
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
const app = new Hono()
// Default protection validates 'origin' and 'sec-fetch-site'
app.use('*', csrf())Warning
CSRF protection is generally not required for GET or HEAD requests. The csrf middleware automatically skips these safe methods.
c): An object passed to your handlers containing request data, response helpers, and environment variables.timingSafeEqual. This prevents "timing attacks" where an attacker guesses a secret by measuring how long the comparison takes.WWW-Authenticate Header: Used by authentication middleware to inform the client which authentication scheme to use when a request is denied.Important
If you are building an API, ensure you use bearerAuth for token validation and cors to manage allowed origins. For user-facing forms, csrf is highly recommended to ensure the requests originate from your own application.