2.4 KiB
2.4 KiB
middleware/context-augmentation
Purpose
This module installs the canonical Hono ContextVariableMap
augmentation that lets every consumer call c.get("user") and
c.get("session") with full type narrowing. Without this declaration
those calls would resolve to unknown, forcing every plugin to cast at
the call site.
Features
- Declares
user: Principal | nullandsession: BetterAuthSessionResulton Hono's globalContextVariableMapinterface. - Side-effect-only export — importing the module wires the augmentation into TypeScript's global module registry.
- Re-exported transitively via every middleware module so consumers importing any auth middleware automatically inherit the augmentation.
Usage: Basic
import "@suaveplan/api-plugin-auth/middleware/session";
// or
import "@suaveplan/api-plugin-auth";
// c.get("user") now narrows to Principal | null everywhere.
Usage: Advanced
Combine the augmentation with requireAuth() so downstream handlers
get a non-null Principal directly. The type system cannot prove the
narrowing through a middleware chain, but explicit destructuring keeps
the call site clean:
import { requireAuth } from "@suaveplan/api-plugin-auth/middleware";
app.use("/me", requireAuth());
app.get("/me", (c) => {
const principal = c.get("user");
if (principal === null) throw new Error("unreachable");
return c.json({ id: principal.id });
});
API Reference
Module augmentation
declare module "hono" {
interface ContextVariableMap {
user: Principal | null;
session: BetterAuthSessionResult;
}
}
The module exports export {} — there are no runtime exports, only the
ambient declaration.
Implementation Notes
- The augmentation is intentionally re-exported as a side effect from
every middleware module's barrel so a single
import "@suaveplan/api-plugin-auth"is enough to enable the typed context everywhere — no separate "augmentation" import is needed. sessionis typed as theBetterAuthSessionResult(a| nullunion) rather than the bareBetterAuthSessionViewso anonymous contexts type-check without a cast.- Augmenting third-party type definitions is the standard pattern for Hono plugins; the auth plugin owns these two slots and no other plugin should re-declare them. Sibling plugins layer their own slots via additional augmentations.