Reusable Permission Check Functions
You'll learn how to build clean, testable utility functions that centralize permission-checking logic across your application.
The Core Idea
Instead of scattering permission checks throughout your codebase with repeated if statements, you create dedicated utility functions that handle all permission logic in one place. This makes your code DRY (Don't Repeat Yourself), easier to test, and simpler to maintain when authorization rules change.
Think of it like a security checkpoint at a building entrance—rather than having every room verify credentials separately, one guard station validates access using consistent rules.
Single Permission Check
// utils/permissions.js
export function hasPermission(user, permission) {
if (!user || !user.permissions) return false;
return user.permissions.includes(permission);
}
// Usage in components
if (hasPermission(currentUser, 'edit_posts')) {
// Show edit button
}
Multiple Permission Checks
// Check if user has ALL permissions (AND logic)
export function hasAllPermissions(user, permissions) {
if (!user || !user.permissions) return false;
return permissions.every(permission =>
user.permissions.includes(permission)
);
}
// Check if user has ANY permission (OR logic)
export function hasAnyPermission(user, permissions) {
if (!user || !user.permissions) return false;
return permissions.some(permission =>
user.permissions.includes(permission)
);
}
// Usage
if (hasAllPermissions(user, ['edit_posts', 'publish_posts'])) {
// Enable publish workflow
}
if (hasAnyPermission(user, ['view_analytics', 'view_reports'])) {
// Show insights dashboard
}
Why This Matters
These functions are pure, testable, and reusable everywhere—components, routes, action handlers. When authorization logic changes, you update one file instead of hunting through dozens of components.
Key Takeaway: Centralizing permission checks in utility functions creates a single source of truth for authorization logic, making your codebase cleaner, more maintainable, and easier to test.