What it does
Ownership middleware verifies that the user owns (or has permission to edit) a resource before allowing the request. It combines two checks: ownership (direct access) and permissions (role-based access).
When to use it
Use ownership checks when:
- Users should edit only their own resources (posts, comments, profiles)
- Admins or moderators need override access
- You want to prevent one user from editing another's data
- Your app has a concept of "ownership" or "creator"
How it works
- Get the resource ID from route params (
req.params.id) - Load the resource from the database
- Check ownership — is the user the owner?
- If owner — allow the request (call
next()) - If not owner — check for permission (e.g.,
posts.moderate) - If permission granted — allow the request
- Otherwise — send 403 Forbidden
This pattern lets both owners and authorized admins edit resources.
Examples
import express from "express";
import { perms } from "./permly.js";
const app = express();
// Example: posts with user_id (owner)
const posts = {
1: { id: 1, title: "My Post", user_id: 42, content: "Hello" },
2: { id: 2, title: "Public Post", user_id: 99, content: "World" },
};
async function ownsPost(req, res, next) {
const userId = req.user?.id;
const postId = req.params.id;
const post = posts[postId];
if (!post) return res.status(404).json({ error: "Post not found" });
// Owner can always edit
if (post.user_id === userId) return next();
// Otherwise, check permission
const allowed = await perms.user(userId).can("posts.edit");
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
}
app.put("/posts/:id", ownsPost, (req, res) => {
const post = posts[req.params.id];
res.json({ message: "Post updated", post });
});
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 | number };
params: { id: string };
}
interface Post {
id: number;
title: string;
user_id: string | number;
content: string;
}
const posts: Record<string, Post> = {
1: { id: 1, title: "My Post", user_id: 42, content: "Hello" },
2: { id: 2, title: "Public Post", user_id: 99, content: "World" },
};
async function ownsPost(req: AuthRequest, res: Response, next: NextFunction) {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: "Not authenticated" });
const postId = req.params.id;
const post = posts[postId];
if (!post) return res.status(404).json({ error: "Post not found" });
if (post.user_id === userId) return next();
const allowed: boolean = await perms.user(userId).can("posts.edit");
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
}
app.put("/posts/:id", ownsPost, (req: AuthRequest, res: Response) => {
const post = posts[req.params.id];
res.json({ message: "Post updated", post });
});
app.listen(3000);
Ownership factory for reuse
Create a factory to generate ownership middleware for any resource:
import express from "express";
import { perms } from "./permly.js";
const app = express();
const posts = {
1: { id: 1, title: "Post 1", user_id: 42 },
2: { id: 2, title: "Post 2", user_id: 99 },
};
const comments = {
1: { id: 1, post_id: 1, user_id: 42, text: "Comment" },
2: { id: 2, post_id: 1, user_id: 99, text: "Reply" },
};
// Factory: create ownership middleware for any resource type
function owns(resourceType, getResource, ownerField) {
return async (req, res, next) => {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: "Not authenticated" });
const resourceId = req.params.id;
const resource = getResource(resourceId);
if (!resource) {
return res.status(404).json({ error: `${resourceType} not found` });
}
// Check ownership
if (resource[ownerField] === userId) return next();
// Permission check: for posts use "posts.edit", for comments use "comments.delete"
const allowed = await perms.user(userId).can("posts.edit");
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
};
}
// Use factory for different resource types
app.put("/posts/:id", owns("posts", (id) => posts[id], "user_id"), (req, res) => {
res.json({ message: "Post updated" });
});
app.put("/comments/:id", owns("comments", (id) => comments[id], "user_id"), (req, res) => {
res.json({ message: "Comment 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 | number };
params: { id: string };
}
interface OwnedResource {
id: number;
[key: string]: string | number;
}
const posts: Record<string, OwnedResource> = {
1: { id: 1, title: "Post 1", user_id: 42 },
2: { id: 2, title: "Post 2", user_id: 99 },
};
function owns(
resourceType: string,
getResource: (id: string) => OwnedResource | undefined,
ownerField: string,
) {
return async (req: AuthRequest, res: Response, next: NextFunction) => {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: "Not authenticated" });
const resourceId = req.params.id;
const resource = getResource(resourceId);
if (!resource) {
return res.status(404).json({ error: `${resourceType} not found` });
}
if (resource[ownerField] === userId) return next();
const allowed: boolean = await perms.user(userId).can("posts.edit");
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
};
}
app.put("/posts/:id", owns("posts", (id) => posts[id], "user_id"), (req: AuthRequest, res: Response) => {
res.json({ message: "Post updated" });
});
app.listen(3000);
Combine with guards
Use ownership middleware before a guard to check both ownership and permissions:
import express from "express";
import { perms } from "./permly.js";
const app = express();
const posts = {
1: { id: 1, title: "Post", user_id: 42, published: false },
};
async function ownsPost(req, res, next) {
const userId = req.user?.id;
const post = posts[req.params.id];
if (!post) return res.status(404).json({ error: "Post not found" });
if (post.user_id === userId) return next();
const allowed = await perms.user(userId).can("posts.edit");
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
}
async function canPublish(req, res, next) {
const userId = req.user?.id;
const allowed = await perms.user(userId).can("posts.publish");
if (!allowed) return res.status(403).json({ error: "Cannot publish" });
next();
}
// Apply ownership check, then permission check
app.post("/posts/:id/publish", ownsPost, canPublish, (req, res) => {
const post = posts[req.params.id];
post.published = true;
res.json({ message: "Post published", post });
});
app.listen(3000);
import express, { Request, Response, NextFunction } from "express";
import { perms } from "./permly.js";
const app = express();
interface AuthRequest extends Request {
user?: { id: number };
params: { id: string };
}
interface Post {
id: number;
title: string;
user_id: number;
published: boolean;
}
const posts: Record<string, Post> = {
1: { id: 1, title: "Post", user_id: 42, published: false },
};
async function ownsPost(req: AuthRequest, res: Response, next: NextFunction) {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ error: "Not authenticated" });
const post = posts[req.params.id];
if (!post) return res.status(404).json({ error: "Post not found" });
if (post.user_id === userId) return next();
const allowed: boolean = await perms.user(userId).can("posts.edit");
if (!allowed) return res.status(403).json({ error: "Permission denied" });
next();
}
async function canPublish(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("posts.publish");
if (!allowed) return res.status(403).json({ error: "Cannot publish" });
next();
}
app.post("/posts/:id/publish", ownsPost, canPublish, (req: AuthRequest, res: Response) => {
const post = posts[req.params.id];
post.published = true;
res.json({ message: "Post published", post });
});
app.listen(3000);
Common mistakes
Trusting user input — Never trust that req.params.id is valid. Always load the resource from the database.
Forgetting owner type check — If post.user_id is a string and req.user.id is a number, the comparison will fail. Convert both to the same type.
Not handling missing resources — If the resource doesn't exist, return 404, not 403. This prevents attackers from guessing resource IDs.
Checking permission before ownership — Always check ownership first. It's faster and more direct than a permission lookup.
Related pages
- Middleware Functions — Write custom middleware
- Guard Factory — Create route guards
- Using with Auth — Integrate with authentication
- Error Handling — Handle permission errors