expressMiddleware

View as MarkdownOpen in Claude

Create an Express/Connect-compatible middleware function that validates incoming requests against the configured authentication methods and returns a 401 Unauthorized response when auth fails. Framework-agnostic equivalent of the Python SDK’s get_fastapi_dependency.

For Hono apps, use middleware() instead. For standalone validation without a framework, use validate() directly.

Parameters

optional
booleanDefaults to false

When true, unauthenticated requests are allowed through instead of being rejected. Useful for progressive-auth flows where the handler downstream decides whether to require credentials.

Returns

An async Express-compatible middleware: (req, res, next) => Promise<void>.

On failed auth with optional=false, responds with HTTP 401 and body { error: 'Unauthorized' }. On success or when optional=true, calls next().

Example

1import express from 'express';
2import { AuthHandler } from '@signalwire/sdk';
3
4const auth = new AuthHandler({
5 bearerToken: 'sk_live_abc123',
6});
7
8const app = express();
9
10// Protect all /api/* routes
11app.use('/api', auth.expressMiddleware());
12
13app.get('/api/status', (req, res) => {
14 res.json({ ok: true });
15});
16
17// Public route with optional auth
18app.get('/public', auth.expressMiddleware(true), (req, res) => {
19 res.json({ authenticated: false });
20});