Advanced Route Features
XyPriss Router exposes three production-critical features directly on the route definition object: Rate Limiting, Response Caching, and Lifecycle Hooks.
Rate Limiting
Per-route rate limiting is enforced natively, offloading the tracking logic to the XHSC core for maximum efficiency.
typescript
router.get(
"/api/export",
{
rateLimit: {
max: 10,
window: "1m", // 10 requests per minute
message: "Rate limit exceeded. Please retry in 1 minute.",
keyBy: "ip", // or "user", or a custom (req) => string
},
},
(req, res) => {
res.json({ data: "Sensitive export data" });
},
);Response Caching
Cache the response of GET routes in-memory to eliminate redundant handler invocations and database lookups.
typescript
router.get("/api/products", { cache: "5m" }, (req, res) => {
// This handler runs once per 5 minutes;
// subsequent hits are served from the native cache.
const products = db.getAll();
res.json({ products });
});Mutation Safety
Caching applies exclusively to
GET routes. Mutation endpoints (POST, PUT, PATCH, DELETE) are never cached.Lifecycle Hooks
Hooks intercept the request at precisely defined stages without interfering with the normal handler chain.
beforeEnter
Runs before the main handler. Use for validation.
afterLeave
Runs after the response is sent. Use for metrics.
onError
Fires if a hook or handler throws. For structured errors.
Hook Implementation
router.get(
"/api/users/:id",
{
lifecycle: {
beforeEnter(req, res, next) {
if (!req.params.id.match(/^\d+$/)) {
return res.status(400).json({ error: "Invalid ID" });
}
next();
},
afterLeave(req, res) {
// Fires after response is sent—safe for async analytics
analytics.track("user.viewed", { id: req.params.id });
},
},
},
(req, res) => {
res.json({ userId: req.params.id });
},
);onError Protocol
Inside an
onError hook, you must terminate the request by responding to the client or throwing the error. Callingnext() will cause the request to hang indefinitely.Live Inspection
Learn how to inspect your routing tree and debug your API routes in real-time.
