Authorization in Node.js
๐ Covered in this chapter:
Role-Based Access ยท Route Protection Middleware ยท Resource Ownership ยท Permissions
Control what authenticated users are allowed to do using role-based and resource-based authorization.
1Authorization in Node.js โ What You'll Learn
Control what authenticated users are allowed to do using role-based and resource-based authorization.
Here's everything this chapter covers, in the order you'll learn it:
- Role-based authorization
- Admin vs user roles
- Fine-grained permissions
- Route protection
- Middleware-based protection
- Resource ownership checks (e.g. 'can this user edit THIS post')
- Policy-based authorization
- API-level permission checks
- Multi-tenant authorization basics
2Working Example
๐ป Example: Authorization in Node.js
JavaScript
โถ Run in Compiler
function requireRole(role) {
return (request, response, next) => {
if (request.user?.role !== role) {
return response.status(403).json({ message: "Forbidden" });
}
next();
};
}
app.delete("/api/courses/:id", requireRole("admin"), deleteCourseHandler);
3Best Practices & Common Pitfalls
๐ก Key things to remember:
- Authentication answers 'who are you?'; authorization answers 'what are you allowed to do?' โ the two are related but distinct layers.
- Always check resource ownership on the server (e.g. a user can only edit their own posts) โ never trust a hidden frontend button as your only protection.
โ Frequently Asked Questions (FAQ)
Q What's the most important thing to understand about authorization in node.js?
Focus on: Role-Based Access ยท Route Protection Middleware ยท Resource Ownership ยท Permissions. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Do I need external npm packages for authorization in node.js?
Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ otherwise, this chapter relies entirely on Node.js's own built-in capabilities.