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 ValueHTTP EffectBehavior
true200 OKPasses—the next guard or handler runs.
false403 ForbiddenBlocks the request immediately.
string401 UnauthorizedBlocks 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).

typescript
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.

typescript
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.

Router-level Guards
Group-level Guards
Route-level Guards
Enforcement
There is no way to bypass a group or router guard from within a child route. Guards ensure that your security policy is strictly enforced top-down.
Advanced Features

Optimize your routes with per-route rate limiting, response caching, and hooks.