bearerAuth
Middleware to protect routes using Bearer tokens (JWTs or API tokens). It reads the Authorization header, validates the token, and continues or blocks the request.
Import
import { bearerAuth } from "tezx/middleware";Options
type BearerAuthOptions = {
validate: (token: string, ctx: Context) => boolean | Promise<boolean>;
realm?: string;
onUnauthorized?: (ctx: Context, error?: Error) => HttpBaseResponse;
};validate Your function to check whether the token is valid.
realm
Shown in WWW-Authenticate header. Default: "API".
onUnauthorized Custom response when validation fails. If not provided, TezX returns:
401WWW-Authenticate: Bearer realm="<realm>"{ error: "<reason>" }
How It Works
-
Reads
Authorizationheader. -
Must match:
Bearer <token>. -
Extracts token.
-
Calls
validate(token, ctx). -
If valid → request continues.
-
If invalid → unauthorized response.
-
If valid, TezX attaches:
(ctx as any).token = token
You can also attach custom user data inside validate().
Examples
Static Token
const auth = bearerAuth({
validate: (token) => token === "dev-token"
});
app.get("/secure", auth, (ctx) => ctx.json({ ok: true }));JWT Validation
import jwt from "tezx/jwt";
const auth = bearerAuth({
validate: (token, ctx) => {
try {
ctx.user = jwt.verify(token, process.env.JWT_SECRET);
return true;
} catch {
return false;
}
}
});Custom Unauthorized Response
const auth = bearerAuth({
validate: verifyToken,
onUnauthorized: (ctx, err) => {
return ctx.status(401).json({ error: "Unauthorized", reason: err?.message });
}
});Accessing the Token / User
app.get("/me", auth, (ctx) => {
const user = (ctx as any).user;
return ctx.json({ user });
});Notes
- Always use HTTPS.
- Tokens are sent on every request—keep them short-lived.
- For JWTs, validate signature, expiry, issuer, and audience.
- Avoid logging sensitive tokens.
basicAuth
The basicAuth middleware enforces HTTP Basic Authentication on incoming requests. It verifies the Authorization, Basic... header, checks credentials, and blocks unauthorized clients.
cacheControl
A compact yet powerful HTTP caching middleware for TezX — built for speed, clarity, and zero overhead.