What it does
Integrating permly with authentication middleware lets you check permissions after you've authenticated the user. Authentication identifies who you are; permissions control what you can do. permly sits downstream of your auth layer.
When to use it
Every app needs this pattern:
- You have authentication middleware (Passport, JWT, session cookies)
- You need to check permissions on protected routes
- You want to combine auth checks with permission checks in a single flow
This is the typical Express security pattern: authenticate first (who are you?), then authorize (what can you do?).
How it works
- Authenticate request — middleware populates
req.userwith the logged-in user - permly checks permissions — reads
req.user.idand checks roles/permissions - Grant or deny — call
next()if allowed, send error if denied
The key is that authentication middleware runs before permly guards, so req.user is always available.
Examples
import express from "express";
import { perms } from "./permly.js";
const app = express();
// Example: simple session auth (in real apps, use Passport or similar)
const users = {
1: { id: 1, email: "alice@example.com", role: "admin" },
2: { id: 2, email: "bob@example.com", role: "viewer" },
};
// Authentication middleware: populate req.user from session
app.use((req, res, next) => {
const userId = req.query.userId; // In real apps, read from session/JWT
if (userId) {
req.user = users[userId];
}
next();
});
// Permission guard: check after auth middleware
async function canEditPosts(req, res, next) {
if (!req.user) return res.status(401).json({ error: "Not authenticated" });
const allowed = await perms.user(req.user.id).can("posts.edit");
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
}
// Assign roles at startup
await perms.sync();
await perms.role("admin").givePermission("posts.edit", "posts.delete");
app.put("/posts/:id", canEditPosts, (req, res) => {
res.json({ message: "Post updated" });
});
app.listen(3000);
import express, { Request, Response, NextFunction } from "express";
import { perms } from "./permly.js";
const app = express();
interface AuthUser {
id: string;
email: string;
role: string;
}
interface AuthRequest extends Request {
user?: AuthUser;
}
const users: Record<string, AuthUser> = {
1: { id: "1", email: "alice@example.com", role: "admin" },
2: { id: "2", email: "bob@example.com", role: "viewer" },
};
app.use((req: AuthRequest, res: Response, next: NextFunction) => {
const userId = req.query.userId as string | undefined;
if (userId) {
req.user = users[userId];
}
next();
});
async function canEditPosts(req: AuthRequest, res: Response, next: NextFunction) {
if (!req.user) return res.status(401).json({ error: "Not authenticated" });
const allowed: boolean = await perms.user(req.user.id).can("posts.edit");
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
}
await perms.sync();
await perms.role("admin").givePermission("posts.edit", "posts.delete");
app.put("/posts/:id", canEditPosts, (req: AuthRequest, res: Response) => {
res.json({ message: "Post updated" });
});
app.listen(3000);
With Passport authentication
Use Passport for production authentication:
// @typecheck-only: needs passport and passport-local npm packages
import express from "express";
import passport from "passport";
import { Strategy as LocalStrategy } from "passport-local";
import { perms } from "./permly.js";
const app = express();
// Passport strategy (simplified)
passport.use(
new LocalStrategy((username, password, done) => {
const user = { id: 1, username, role: "editor" };
done(null, user);
})
);
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => {
const user = { id, username: "alice", role: "editor" };
done(null, user);
});
app.use(passport.initialize());
app.use(passport.session());
// Permission guard works after Passport middleware
function guard(permission) {
return async (req, res, next) => {
if (!req.user) return res.status(401).json({ error: "Not authenticated" });
const allowed = await perms.user(req.user.id).can(permission);
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
};
}
app.post("/login", passport.authenticate("local"), (req, res) => {
res.json({ message: "Logged in" });
});
app.delete("/posts/:id", guard("posts.delete"), (req, res) => {
res.json({ message: "Post deleted" });
});
app.listen(3000);
// @typecheck-only: needs passport and real authentication strategy
import express, { Request, Response, NextFunction } from "express";
import passport from "passport";
import { Strategy as LocalStrategy } from "passport-local";
import type { InferPermission } from "permly";
import { perms } from "./permly.js";
const app = express();
interface AuthUser {
id: string | number;
username: string;
role: string;
}
interface AuthRequest extends Request {
user?: AuthUser;
}
passport.use(
new LocalStrategy((username: string, password: string, done: (err: null, user: AuthUser) => void) => {
const user: AuthUser = { id: 1, username, role: "editor" };
done(null, user);
})
);
passport.serializeUser((user: AuthUser, done: (err: null, id: string | number) => void) => done(null, user.id));
passport.deserializeUser((id: string | number, done: (err: null, user: AuthUser) => void) => {
const user: AuthUser = { id, username: "alice", role: "editor" };
done(null, user);
});
app.use(passport.initialize());
app.use(passport.session());
type Permission = InferPermission<typeof perms>;
function guard(permission: Permission) {
return async (req: AuthRequest, res: Response, next: NextFunction) => {
if (!req.user) return res.status(401).json({ error: "Not authenticated" });
const allowed: boolean = await perms.user(req.user.id).can(permission);
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
};
}
app.post("/login", passport.authenticate("local"), (req: AuthRequest, res: Response) => {
res.json({ message: "Logged in" });
});
app.delete("/posts/:id", guard("posts.delete"), (req: AuthRequest, res: Response) => {
res.json({ message: "Post deleted" });
});
app.listen(3000);
Middleware order matters
Always apply authentication middleware before permission guards:
import express from "express";
import { perms } from "./permly.js";
const app = express();
// Step 1: Authentication middleware (runs first)
app.use((req, res, next) => {
const token = req.headers.authorization?.split(" ")[1];
if (token) {
// In real apps: verify JWT, fetch user from DB
req.user = { id: 1, name: "Alice" };
}
next();
});
// Step 2: Permission guard (runs after auth)
function requirePermission(permission) {
return async (req, res, next) => {
if (!req.user) return res.status(401).json({ error: "Not authenticated" });
const allowed = await perms.user(req.user.id).can(permission);
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
};
}
// Step 3: Route handler (runs if both checks pass)
app.delete("/posts/:id", requirePermission("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 | number; name: string };
}
type Permission = InferPermission<typeof perms>;
// Step 1: Authentication
app.use((req: AuthRequest, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.split(" ")[1];
if (token) {
req.user = { id: 1, name: "Alice" };
}
next();
});
// Step 2: Permission guard
function requirePermission(permission: Permission) {
return async (req: AuthRequest, res: Response, next: NextFunction) => {
if (!req.user) return res.status(401).json({ error: "Not authenticated" });
const allowed: boolean = await perms.user(req.user.id).can(permission);
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
};
}
// Step 3: Route handler
app.delete("/posts/:id", requirePermission("posts.delete"), (req: AuthRequest, res: Response) => {
res.json({ message: "Post deleted" });
});
app.listen(3000);
Common mistakes
Skipping auth before permissions — If you check permissions before authenticating, req.user is undefined and will error. Always authenticate first.
Assuming roles equal permissions — Don't assume req.user.role alone grants permissions. Always use permly to check, because roles can change in the database.
Hardcoding user IDs — Don't use a fixed user ID in guards. Always read from req.user.id (or req.session.userId for session auth).
Mixing auth and permissions in one check — Keep authentication separate from permissions. Auth answers "who?", permissions answer "what?". Two middleware is cleaner than one.
Related pages
- Middleware Functions — Write custom middleware
- Guard Factory — Create route guards
- Custom Responses — Format error responses
- Error Handling — Handle permission errors