What it does
A guard factory is a higher-order function that returns middleware to protect routes. It's a cleaner way to write permission checks than inline middleware, making your routes more readable and maintainable.
When to use it
Use guards when:
- You have many routes with permission checks
- You want to keep routes concise and readable
- You're building a REST API or GraphQL server
- You want type-safe permission names (TypeScript)
How it works
- Create a factory function — takes permission name(s) and returns middleware
- The middleware checks permissions — extracts user ID, checks permission, calls next() or errors
- Apply to routes — use it like any other middleware stack
- Combine guards — apply multiple guards to enforce multiple permissions
Guards run synchronously in the middleware stack but perform async permission checks internally.
Examples
import express from "express";
import { perms } from "./permly.js";
const app = express();
// Guard factory: create middleware that requires a permission
function guard(permission) {
return async (req, res, next) => {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: "Not authenticated" });
const allowed = await perms.user(userId).can(permission);
if (!allowed) return res.status(403).json({ error: "Forbidden" });
next();
};
}
// Use guards on routes
app.post("/posts", guard("posts.create"), (req, res) => {
res.json({ message: "Post created" });
});
app.put("/posts/:id", guard("posts.edit"), (req, res) => {
res.json({ message: "Post updated" });
});
app.delete("/posts/:id", guard("posts.delete"), (req, res) => {
res.json({ message: "Post deleted" });
});
app.listen(3000);
import express, { Request, Response, NextFunction } from "express";
import type { InferPermission } from "permly";
import { perms } from "./permly.js";
const app = express();
interface AuthRequest extends Request {
user?: { id: string };
}
type Permission = InferPermission<typeof perms>;
function guard(permission: Permission) {
return async (req: AuthRequest, res: Response, next: NextFunction) => {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: "Not authenticated" });
const allowed: boolean = await perms.user(userId).can(permission);
if (!allowed) return res.status(403).json({ error: "Forbidden" });
next();
};
}
app.post("/posts", guard("posts.create"), (req: AuthRequest, res: Response) => {
res.json({ message: "Post created" });
});
app.put("/posts/:id", guard("posts.edit"), (req: AuthRequest, res: Response) => {
res.json({ message: "Post updated" });
});
app.delete("/posts/:id", guard("posts.delete"), (req: AuthRequest, res: Response) => {
res.json({ message: "Post deleted" });
});
app.listen(3000);
Type-safe with TypeScript
Use InferPermission to get autocomplete for all valid permissions:
import type { InferPermission } from "permly";
import { perms } from "./permly.js";
// Permission type is automatically all valid permissions
type Permission = InferPermission<typeof perms>;
function guard(permission: Permission) {
// guard implementation
}
// Calling guard with a valid permission type-checks correctly:
guard("posts.create"); // ✓ OK
// Calling guard with an invalid permission will type-error:
// @ts-expect-error
guard("invalid.permission"); // ✗ Type error
Multiple permissions (AND)
Require all permissions to pass:
import express from "express";
import { perms } from "./permly.js";
const app = express();
// Guard that requires multiple permissions
function guardAny(permissions) {
return async (req, res, next) => {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: "Not authenticated" });
// Check all permissions; user must have all of them
const checks = await Promise.all(
permissions.map((p) => perms.user(userId).can(p))
);
if (!checks.every(Boolean)) {
return res.status(403).json({ error: "Forbidden" });
}
next();
};
}
// User must have both permissions
app.delete("/posts/:id", guardAny(["posts.delete", "posts.edit"]), (req, res) => {
res.json({ message: "Post deleted" });
});
app.listen(3000);
import express, { Request, Response, NextFunction } from "express";
import type { InferPermission } from "permly";
import { perms } from "./permly.js";
const app = express();
interface AuthRequest extends Request {
user?: { id: string };
}
type Permission = InferPermission<typeof perms>;
function guardAny(permissions: Permission[]) {
return async (req: AuthRequest, res: Response, next: NextFunction) => {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: "Not authenticated" });
const checks = await Promise.all(
permissions.map((p) => perms.user(userId).can(p))
);
if (!checks.every(Boolean)) {
return res.status(403).json({ error: "Forbidden" });
}
next();
};
}
app.delete("/posts/:id", guardAny(["posts.delete", "posts.edit"]), (req: AuthRequest, res: Response) => {
res.json({ message: "Post deleted" });
});
app.listen(3000);
Multiple permissions (OR)
Require at least one permission to pass:
import express from "express";
import { perms } from "./permly.js";
const app = express();
// Guard that requires at least one permission
function guardAnyOf(permissions) {
return async (req, res, next) => {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: "Not authenticated" });
// Check all permissions; user must have at least one
const checks = await Promise.all(
permissions.map((p) => perms.user(userId).can(p))
);
if (!checks.some(Boolean)) {
return res.status(403).json({ error: "Forbidden" });
}
next();
};
}
// User must have either edit OR publish permission
app.put("/posts/:id", guardAnyOf(["posts.edit", "posts.publish"]), (req, res) => {
res.json({ message: "Post updated" });
});
app.listen(3000);
import express, { Request, Response, NextFunction } from "express";
import type { InferPermission } from "permly";
import { perms } from "./permly.js";
const app = express();
interface AuthRequest extends Request {
user?: { id: string };
}
type Permission = InferPermission<typeof perms>;
function guardAnyOf(permissions: Permission[]) {
return async (req: AuthRequest, res: Response, next: NextFunction) => {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: "Not authenticated" });
const checks = await Promise.all(
permissions.map((p) => perms.user(userId).can(p))
);
if (!checks.some(Boolean)) {
return res.status(403).json({ error: "Forbidden" });
}
next();
};
}
app.put("/posts/:id", guardAnyOf(["posts.edit", "posts.publish"]), (req: AuthRequest, res: Response) => {
res.json({ message: "Post updated" });
});
app.listen(3000);
Common mistakes
Not checking user exists — Always check req.user?.id before calling permly. Anonymous requests will fail.
Forgetting async/await — Permission checks are async. Always mark the middleware as async and use await on permission checks.
Not handling errors in guards — If the database is down, the permission check might throw. Wrap it in try/catch or use error-handling middleware.
Creating guards inside route definitions — Define guards outside routes (or in a separate file). Guards created for every request are inefficient.
Related pages
- Middleware Functions — Write custom middleware
- Ownership Middleware — Check resource ownership
- Using with Auth — Integrate with authentication
- Error Handling — Handle permission errors gracefully