Middleware
basicAuth
The basicAuth middleware enforces HTTP Basic Authentication on incoming requests. It verifies the Authorization, Basic... header, checks credentials, and blocks unauthorized clients.
When to Use
- Protect admin routes (such as
/admin,/dashboard) - Secure APIs during development or testing without OAuth/JWT
- Add a quick access gate to staging servers
Import
import { basicAuth } from "tezx/middleware";Options
export type BasicAuthOptions = {
/**
* Function to validate credentials.
*/
validate: (
username: string,
password: string,
ctx: Context
) => boolean | Promise<boolean>;
/**
* Authentication realm (shown in browser login popup).
* @default "Restricted Area"
*/
realm?: string;
/**
* Custom handler when authentication fails.
* Must return an HttpBaseResponse.
*/
onUnauthorized?: (ctx: Context, error?: Error) => HttpBaseResponse;
};Usage Examples
1. Static Credentials
import { basicAuth } from "tezx/middleware";
const auth = basicAuth({
validate: (username, password) =>
username === "admin" && password === "secret",
});app.use("/admin", auth, (ctx) => {
ctx.json({ message: "Welcome, admin!" });
});2. Async Validation (Database)
const auth = basicAuth({
validate: async (username, password, ctx) => {
const user = await db.users.findOne({ username });
return user && user.passwordHash === hash(password);
},
});3. Custom Unauthorized Handler
const auth = basicAuth({
validate: (u, p) => u === "demo" && p === "demo",
onUnauthorized: (ctx, error) => {
return ctx.status(401).json({ error: "Access denied", reason: error?.message });
},
});How It Works
- Reads the
Authorizationheader - Checks that it begins with
Basic - Decodes Base64 credentials (
username:password) - Calls your
validate(username, password, ctx) -
- If valid: attaches
ctx.user = { username }and continues - If invalid: calls
onUnauthorizedand stops the request
- If valid: attaches
Accessing the Authenticated User
app.get("/profile", auth, (ctx) => {
const user = (ctx as any).user;
return ctx.json({ message: `Hello ${user.username}` });
});Notes
- Credentials are sent with every request and only Base64-encoded, so use HTTPS.
- For production-grade security, consider JWT, OAuth2, or session-based auth.
- The
realmvalue appears in the browser login popup.
useFormData
useFormData is a powerful helper designed for efficient parsing, validation, and management of multipart/form-data HTTP requests in TezX applications. It simplifies handling complex file uploads combined with form fields while enforcing strict limits to protect your server from overload and security risks.
bearerAuth
Middleware to protect routes using Bearer tokens (JWTs or API tokens).