What it does
Custom response formatting lets you control what message, status code, or data structure clients receive when a permission is denied. Instead of a generic 403 error, you can send application-specific error details.
When to use it
Use custom responses when:
- You want consistent error formats across your API
- You need to distinguish between "not authenticated" (401) and "not authorized" (403)
- You want to include error codes, timestamps, or request IDs in error responses
- You're building a GraphQL or REST API with specific error contracts
How it works
- Check permissions — in your middleware or guard
- If denied — don't just send a 403
- Format a response — include status, message, error code, details
- Send the response — client gets structured error data
Most apps want consistent error formats, so create a helper function instead of repeating the same code in every guard.
Examples
import express from "express";
import { perms } from "./permly.js";
const app = express();
// Helper: send a permission error with consistent format
function permissionDenied(res, message = "Permission denied") {
res.status(403).json({
error: "permission_denied",
message,
timestamp: new Date().toISOString(),
});
}
async function canEditPosts(req, res, next) {
const userId = req.user?.id;
if (!userId) {
return res.status(401).json({
error: "not_authenticated",
message: "You must log in first",
});
}
const allowed = await perms.user(userId).can("posts.edit");
if (!allowed) return permissionDenied(res);
next();
}
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 AuthRequest extends Request {
user?: { id: string };
}
interface ErrorResponse {
error: string;
message: string;
timestamp?: string;
}
function permissionDenied(res: Response, message = "Permission denied"): void {
res.status(403).json({
error: "permission_denied",
message,
timestamp: new Date().toISOString(),
} as ErrorResponse);
}
async function canEditPosts(req: AuthRequest, res: Response, next: NextFunction) {
const userId = req.user?.id;
if (!userId) {
return res.status(401).json({
error: "not_authenticated",
message: "You must log in first",
} as ErrorResponse);
}
const allowed: boolean = await perms.user(userId).can("posts.edit");
if (!allowed) return permissionDenied(res);
next();
}
app.put("/posts/:id", canEditPosts, (req: AuthRequest, res: Response) => {
res.json({ message: "Post updated" });
});
app.listen(3000);
Include error codes
Send error codes that clients can handle programmatically:
import express from "express";
import { perms } from "./permly.js";
const app = express();
// Error codes your client can handle
const ErrorCode = {
PERMISSION_DENIED: "PERMISSION_DENIED",
NOT_AUTHENTICATED: "NOT_AUTHENTICATED",
RESOURCE_NOT_FOUND: "RESOURCE_NOT_FOUND",
};
function sendError(res, code, statusCode, message) {
res.status(statusCode).json({
code,
message,
timestamp: new Date().toISOString(),
});
}
function guard(permission) {
return async (req, res, next) => {
const userId = req.user?.id;
if (!userId) {
return sendError(res, ErrorCode.NOT_AUTHENTICATED, 401, "Not logged in");
}
const allowed = await perms.user(userId).can(permission);
if (!allowed) {
return sendError(res, ErrorCode.PERMISSION_DENIED, 403, "Access denied");
}
next();
};
}
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>;
const ErrorCode = {
PERMISSION_DENIED: "PERMISSION_DENIED" as const,
NOT_AUTHENTICATED: "NOT_AUTHENTICATED" as const,
RESOURCE_NOT_FOUND: "RESOURCE_NOT_FOUND" as const,
};
interface ErrorResponse {
code: typeof ErrorCode[keyof typeof ErrorCode];
message: string;
timestamp: string;
}
function sendError(res: Response, code: typeof ErrorCode[keyof typeof ErrorCode], statusCode: number, message: string): void {
res.status(statusCode).json({
code,
message,
timestamp: new Date().toISOString(),
} as ErrorResponse);
}
function guard(permission: Permission) {
return async (req: AuthRequest, res: Response, next: NextFunction) => {
const userId = req.user?.id;
if (!userId) {
return sendError(res, ErrorCode.NOT_AUTHENTICATED, 401, "Not logged in");
}
const allowed: boolean = await perms.user(userId).can(permission);
if (!allowed) {
return sendError(res, ErrorCode.PERMISSION_DENIED, 403, "Access denied");
}
next();
};
}
app.delete("/posts/:id", guard("posts.delete"), (req: AuthRequest, res: Response) => {
res.json({ message: "Post deleted" });
});
app.listen(3000);
Include permission info in errors
Tell the client which permission was checked:
import express from "express";
import { perms } from "./permly.js";
const app = express();
function createGuard(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: "permission_denied",
required: permission,
message: `This action requires the '${permission}' permission`,
});
}
next();
};
}
app.post("/posts", createGuard("posts.create"), (req, res) => {
res.json({ message: "Post created" });
});
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 createGuard(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: "permission_denied",
required: permission,
message: `This action requires the '${permission}' permission`,
});
}
next();
};
}
app.post("/posts", createGuard("posts.create"), (req: AuthRequest, res: Response) => {
res.json({ message: "Post created" });
});
app.listen(3000);
Common mistakes
Leaking sensitive info — Don't include database errors or stack traces in error responses. Send generic messages like "Access denied", not "User 42 has role 'viewer', not 'editor'".
Inconsistent error formats — If one route returns { error, message } and another returns { code, details }, clients can't handle errors consistently. Use the same format everywhere.
Sending 200 instead of 401/403 — Always send the correct status code. 200 means success; 401 means not authenticated; 403 means forbidden. Clients rely on these codes.
Forgetting timestamps — Include timestamps in errors (especially for debugging in production). new Date().toISOString() is a good default.
Related pages
- Middleware Functions — Write custom middleware
- Guard Factory — Create route guards
- Error Handling — Handle permission errors globally
- Using with Auth — Integrate with authentication