Security Guards & XyGuard
Guards are the primary mechanism for enforcing authorization in XyPriss XyPriss Router. Unlike traditional middleware, guards use a standardized return-type protocol and are fully visible in the route inspection registry.
The Guard Protocol
A guard is a function that receives (req, res) and returns a specific value to determine the request's fate:
| Return Value | HTTP Effect | Behavior |
|---|---|---|
| true | 200 OK | Passes—the next guard or handler runs. |
| false | 403 Forbidden | Blocks the request immediately. |
| string | 401 Unauthorized | Blocks and returns the string as the error message. |
XyGuard API
The XyGuard API provides a non-opinionated security layer for implementing built-in declarative guards . It allows you to keep your route definitions clean while defining logic globally.
Defining Resolvers
Register your logic for the standard guard types (authenticated,roles, permissions).
import { XyGuard } from "xypriss";
// Define global auth logic
XyGuard.define("authenticated", (req) => {
return !!req.session?.get("user_id") || "Login required";
});
// Define role-based access
XyGuard.define("roles", (req, requiredRoles) => {
const userRole = req.locals.user?.role;
return requiredRoles.includes(userRole);
});Usage in Routes
Apply these defined guards directly in the route options object.
app.get(
"/admin/settings",
{
guards: {
authenticated: true,
roles: ["admin"],
},
},
(req, res) => {
res.success("Welcome, Admin");
},
);Guard Inheritance
Guards cascade from the outermost scope inward. Every layer must pass independently to reach the handler.
Optimize your routes with per-route rate limiting, response caching, and hooks.
