API Reference

server.guard

Implement one identity by turning the extracted credential into typed handler context, or denying the request.

server.guard(identity, run) implements one identity: it turns the extracted credential into the typed context handlers receive, or denies the request. One guard per identity; the auth map decides which routes it protects.

src/server/guards.ts
import { server } from './server';

export const requireUser = server.guard('user', ({ bearer, deny }) => {
    const session = bearer ? sessions.get(bearer.token) : undefined;
    if (!session) {
        return deny(401, 'Unauthorized');
    }
    return {
        userId: session.userId,
    };
});

The credential arrives already parsed and typed, keyed by the identity's method (bearer, apiKey, basic, oauth2, openIdConnect), or null when the request carried none. Return the identity's context and access fields to allow the request; they reach handlers under auth, keyed by the identity's name. An authentication-only identity returns nothing on success.

Guard arguments:

PropertyDescription
credentialThe extracted credential, keyed by the identity's method. null when absent.
paramsThe matched route's path params, for guards that check access to the resource in the URL.
deny(status, detail) => GuardDenial, rejects with a Problem Details response.
scopesThe matched route's required OAuth scopes (string[], empty for non-scoped routes).
framework contextThe adapter's native request objects (req/res, c, request/reply, request).