middleware

View as MarkdownOpen in Claude

Create a Hono-compatible middleware function that validates incoming requests against the configured auth methods. Unauthorized requests receive a 401 Unauthorized JSON response by default; pass optional: true to let them pass through without blocking.

Parameters

optional
booleanDefaults to false

When true, unauthenticated requests are allowed through instead of being rejected with a 401. Useful for routes that expose richer data to authenticated callers but still serve unauthenticated traffic.

Returns

(c: any, next: () => Promise<void>) => Promise<Response | void> — A middleware function suitable for use with Hono’s app.use().

Example

1import { AuthHandler } from '@signalwire/sdk';
2import { Hono } from 'hono';
3
4const auth = new AuthHandler({
5 bearerToken: process.env.AUTH_TOKEN,
6});
7const app = new Hono();
8
9// Protect all routes — unauthorized returns 401
10app.use('*', auth.middleware());
11
12app.get('/', (c) => c.json({ status: 'ok' }));
13
14// Or allow unauthenticated access through
15app.use('/public/*', auth.middleware(true));