Role-Based Access Control: Type-Safe RBAC in TypeScript
Build a type-safe RBAC system in TypeScript, create a unified can() function, sync permissions across UI and backend, and learn when RBAC reaches its limits.
Post 102 centralized authorization in the service layer, solving the architectural question of where permission checks happen. But the permission rules inside the service layer are still hardcoded if/else chains: if (session.role === 'admin') return true. Adding a new role means modifying every helper function across every service file.
RBAC (Role-Based Access Control) replaces those chains. Ferraiolo and Kuhn formalized the model in 1992, and the NIST model became the ANSI/INCITS 359-2004 standard (revised in 2012). A single, type-safe can() function takes over the hardcoded role checks. It runs on both server and client, closing the permission logic duplication that Post 102 left open.
The role that goes into can() is the one the user holds in the project being accessed. That keeps project membership inside RBAC and leaves only document ownership and document state for ABAC in Post 104.
What Is RBAC?#
The NIST Model#
RBAC assigns permissions to roles, not directly to users. Users acquire permissions by being assigned to roles. This indirection is the core insight: when someone changes jobs, you change their role and fifty individual permissions follow.
The core of the NIST model has four parts:
- Users: Authenticated identities (from
verifySession()in our case) - Roles: Named job functions: admin, editor, author, viewer
- Permissions: Approved operations on resources:
document:create,project:read - Sessions: The link between a user and the roles active for a piece of work. One user can hold several sessions with different roles at the same time.
The standard builds two levels on top of this core. Hierarchical RBAC lets a senior role inherit the permissions of a junior role. Constrained RBAC adds separation of duty: rules that stop one person from holding two roles that check each other. Both appear in code below.
Without roles, managing permissions requires N users times M permissions assignments. With roles, you manage a much smaller set: N user-to-role assignments plus R role-to-permission mappings.
RBAC in Our Domain#
Mapping NIST concepts to the domain from Posts 101-102:
| NIST Concept | Our Domain |
|---|---|
| User | Authenticated session from verifySession() |
| Role | admin, editor, author, viewer |
| User-role assignment | Global admin on the user record; every other role per project (project.ownerId and project.members) |
| Session | One request; the active role is the one held in the requested project |
| Object (Resource) | document, project |
| Operation (Action) | create, read, update, delete, publish |
| Permission | Role-to-(resource, action) mapping |
Users connect to roles, and roles connect to permissions. No user connects to a permission directly, and that indirection is the whole of the RBAC structure.
TypeScript Permission Definitions#
Resources and Actions#
The first step is defining what resources and actions exist. TypeScript’s as const assertion preserves literal types instead of widening to string[].
// lib/permissions.ts
// No 'server-only' -- this file is shared between server and client
export const RESOURCES = ['document', 'project'] as const;
export type Resource = (typeof RESOURCES)[number];
export const ACTIONS = [
'create',
'read',
'update',
'delete',
'publish',
] as const;
export type Action = (typeof ACTIONS)[number];
// Template literal type: "document:create" | "document:read" | ...
export type Permission = `${Resource}:${Action}`;
The Permission type is a union of all valid Resource:Action combinations. Writing 'document:fly' would be a compile-time error. TypeScript generates this union automatically from the two as const arrays.
Roles#
export const ROLES = ['admin', 'editor', 'author', 'viewer'] as const;
export type Role = (typeof ROLES)[number];
The Permission Map#
This is the core of the RBAC system: a single object that defines every role’s permissions.
export const ROLE_PERMISSIONS = {
admin: [
'document:create',
'document:read',
'document:update',
'document:delete',
'document:publish',
'project:create',
'project:read',
'project:update',
'project:delete',
],
editor: [
'document:create',
'document:read',
'document:update',
'document:publish',
'project:read',
],
author: [
'document:create',
'document:read',
'document:update',
'project:read',
],
viewer: [
'document:read',
'project:read',
],
} as const satisfies Record<Role, readonly Permission[]>;
Two TypeScript features work together here:
as constpreserves literal types; each permission is'document:create', notstringsatisfiesvalidates the shape without widening. If a role is misspelled or a permission string is invalid (like'document:fly'), TypeScript catches it at compile time. But the inferred type still retains the specific literal values, enabling autocomplete
Why satisfies instead of a type annotation? Writing const ROLE_PERMISSIONS: Record<Role, Permission[]> would widen all values to Permission[], losing the specific literal information. With satisfies, TypeScript knows exactly which permissions each role has.
The Permission Matrix#
The ROLE_PERMISSIONS object above can be visualized as a table. This table is reviewable, auditable, and does not require reading code.
| Permission | admin | editor | author | viewer |
|---|---|---|---|---|
| document:create | yes | yes | yes | — |
| document:read | yes | yes | yes | yes |
| document:update | yes | yes | yes | — |
| document:delete | yes | — | — | — |
| document:publish | yes | yes | — | — |
| project:create | yes | — | — | — |
| project:read | yes | yes | yes | yes |
| project:update | yes | — | — | — |
| project:delete | yes | — | — | — |
“What can an editor do?” is answered at a glance. The table is a view of the map, though, and a hand-written copy drifts from the code. Generate it from ROLE_PERMISSIONS with a small script, or pin it with a snapshot test, so a change to the map fails CI until the table changes too.
Role Inheritance#
The admin list repeats every editor permission, and the editor list repeats every author permission. Hierarchical RBAC removes that repetition: a senior role holds its own permissions plus everything its juniors hold.
const ROLE_HIERARCHY = {
admin: ['editor'],
editor: ['author'],
author: ['viewer'],
viewer: [],
} as const satisfies Record<Role, readonly Role[]>;
const DIRECT_PERMISSIONS = {
admin: [
'document:delete',
'project:create',
'project:update',
'project:delete',
],
editor: ['document:publish'],
author: ['document:create', 'document:update'],
viewer: ['document:read', 'project:read'],
} as const satisfies Record<Role, readonly Permission[]>;
// A senior role inherits everything its juniors hold
export function resolvePermissions(role: Role): Set<Permission> {
const result = new Set<Permission>(DIRECT_PERMISSIONS[role]);
for (const junior of ROLE_HIERARCHY[role]) {
for (const permission of resolvePermissions(junior)) {
result.add(permission);
}
}
return result;
}
resolvePermissions('editor') returns the same five permissions as the flat editor list. The flat map stays easier to review; the hierarchy pays off once roles share long lists. If both exist, a test that compares them for every role keeps them in sync:
it('resolves to the same permissions as ROLE_PERMISSIONS', () => {
for (const role of ROLES) {
expect([...resolvePermissions(role)].sort()).toEqual(
[...ROLE_PERMISSIONS[role]].sort()
);
}
});
The can() Function#
Implementation#
can() takes a role, a resource, and an action, then answers with a boolean.
// lib/permissions.ts (continued)
export function can(
role: Role,
resource: Resource,
action: Action
): boolean {
const permissions = ROLE_PERMISSIONS[role];
const required = `${resource}:${action}` as Permission;
return (permissions as readonly Permission[]).includes(required);
}
// Alternative: check with a full permission string
export function hasPermission(
role: Role,
permission: Permission
): boolean {
return (ROLE_PERMISSIONS[role] as readonly Permission[]).includes(
permission
);
}
Key characteristics:
- Pure function: No database access, no async, no side effects. The cost per call is negligible: one lookup in a short array.
- Type-safe at compile time:
rolemust be one of four literal types, and invalid resource or action strings are compile-time errors. At runtime the role still arrives as a string from a token or a database row. Without a check, an unknown role makesROLE_PERMISSIONS[role]undefined, and.includesthrows a TypeError. TheisRole()guard in the next section closes that gap. - Two forms:
can(role, 'document', 'update')reads naturally in service methods.hasPermission(role, 'document:update')reads naturally in UI components. Both query the sameROLE_PERMISSIONSmap.
Project-Scoped Roles#
can() answers for whatever role it receives, so the design decision that matters is which role goes in. Post 102 used two. session.role is the global role (admin or member), which verifySession() reads from the users table, and Post 102’s service layer consulted it only for the admin bypass. The project role comes from projectRoleOf(): owner from project.ownerId, everything else from the membership row. Post 102’s UI guard copied the edit rule from the DTO’s viewerRole, and that copy is the drift this refactor removes.
A shortcut would store one role from the map on the user record and pass session.role to can() for everyone. That would be a regression. The map grants document:update to author, so every author could edit every document in every project: the horizontal escalation from Post 101. Role assignment has to stay per project. In NIST terms, “editor in project A” and “editor in project B” act as two roles that share one permission set, and project.ownerId plus project.members are the user-role assignment. A user with no role in a project gets no permissions there.
// lib/permissions.ts (continued)
// A role from a token or a database row is only a string at runtime
export function isRole(value: unknown): value is Role {
return (
typeof value === 'string' &&
(ROLES as readonly string[]).includes(value)
);
}
interface ProjectMember {
userId: string;
role: string; // as stored in the database
}
// The role that applies to this user inside this project
export function effectiveRole(
session: { userId: string; role: string },
project: { ownerId: string; members: ProjectMember[] }
): Role | null {
// The global admin is the only platform-wide assignment
if (session.role === 'admin') return 'admin';
// Project ownership comes first, as in Post 102's projectRoleOf().
// There the project owner holds the same document rights as an editor.
if (project.ownerId === session.userId) return 'editor';
// Everyone else holds a role per project in a membership row
const membership = project.members.find(
(m) => m.userId === session.userId
);
// Unknown roles ("superadmin", a renamed legacy role) fail closed
return membership && isRole(membership.role) ? membership.role : null;
}
In lib/permissions.ts, effectiveRole() is the only place that reads the global role, and it never casts. A global role other than admin (Post 102’s member, or an unknown value) grants nothing by itself, and an unknown role in a membership row becomes null. Every caller treats null as “no access”. The project owner (project.ownerId) maps to editor because Post 102 gives owners and editors the same document rights. This is project ownership; the ownership checks below concern the document’s author. The function repeats projectRoleOf() instead of importing it because Post 102’s helper lives in a server-only module, while lib/permissions.ts also runs in the browser.
Before and After: Service Layer Refactoring#
Before (hardcoded checks from Post 102):
function canEditDocument(
session: SessionUser,
document: DocumentWithProject
): boolean {
if (session.role === 'admin') return true;
const role = projectRoleOf(session, document.project);
// Owners and editors can edit any document in the project
if (role === 'owner' || role === 'editor') return true;
// Authors can edit their own documents
return role === 'author' && document.authorId === session.userId;
}
After (RBAC with can()):
// lib/permissions.ts (continued): pure, so the service layer and the UI share it
export function canEditDocument(
session: { userId: string; role: string },
document: {
authorId: string;
project: { ownerId: string; members: ProjectMember[] };
}
): boolean {
const role = effectiveRole(session, document.project);
// Role check on the project-scoped role; no role means no access
if (role === null || !can(role, 'document', 'update')) return false;
// Ownership limits authors to their own documents
// (This is where RBAC reaches its limit -- see Limitations)
if (role === 'author') return document.authorId === session.userId;
return true;
}
What changed:
- The admin and owner special cases moved into
effectiveRole().canEditDocumentaskscan()and never namesadminorowner. can()receives the project role, so a role held in one project grants nothing in a project the user does not belong to. For the global admin and every project role (owner, editor, author, viewer), the decisions match Post 102.- Adding a “moderator” role that can edit documents takes a new name in
ROLESand its entry inROLE_PERMISSIONS(thesatisfiescheck fails until both exist); this function stays untouched. - The ownership check (
document.authorId === session.userId) remains anif. It runs after the role check and can only turn a “yes” into a “no”. RBAC cannot express “only if you own it”; that limit is the motivation for ABAC in Post 104.
A refactor of authorization code needs a test that pins the old behavior. The helper is pure, so the test needs no mocks:
// __tests__/permissions/can-edit-document.test.ts
import { canEditDocument } from '@/lib/permissions';
// A document written by u2 in a project owned by u9
const doc = (members: { userId: string; role: string }[]) => ({
authorId: 'u2',
project: { ownerId: 'u9', members },
});
describe('canEditDocument keeps the Post 102 behavior', () => {
it('denies a member who has no role in the project', () => {
const session = { userId: 'u1', role: 'member' };
const members = [{ userId: 'u3', role: 'editor' }];
expect(canEditDocument(session, doc(members))).toBe(false);
});
it('denies a user whose record holds a map role but who has no row in the project', () => {
const session = { userId: 'u1', role: 'editor' };
expect(canEditDocument(session, doc([]))).toBe(false);
});
it("denies a project author on someone else's document", () => {
const session = { userId: 'u1', role: 'member' };
const members = [{ userId: 'u1', role: 'author' }];
expect(canEditDocument(session, doc(members))).toBe(false);
});
it('allows a project author on their own document', () => {
const session = { userId: 'u2', role: 'member' };
const members = [{ userId: 'u2', role: 'author' }];
expect(canEditDocument(session, doc(members))).toBe(true);
});
it('allows a project editor on any document in the project', () => {
const session = { userId: 'u1', role: 'member' };
const members = [{ userId: 'u1', role: 'editor' }];
expect(canEditDocument(session, doc(members))).toBe(true);
});
it('allows the project owner without a membership row', () => {
const session = { userId: 'u9', role: 'member' };
expect(canEditDocument(session, doc([]))).toBe(true);
});
it('allows the global admin without membership', () => {
const session = { userId: 'u1', role: 'admin' };
expect(canEditDocument(session, doc([]))).toBe(true);
});
it('fails closed on a role the map does not know', () => {
const session = { userId: 'u1', role: 'member' };
const members = [{ userId: 'u1', role: 'superadmin' }];
expect(canEditDocument(session, doc(members))).toBe(false);
});
});
The first test pins the per-project assignment: u1 has no row in this project, so an editor row held by someone else grants u1 nothing. The second pins what the shortcut breaks. With editor stored on the user record, can(session.role, 'document', 'update') returns true in every project, member or not. effectiveRole() ignores that value because it is not admin, so this test fails as soon as session.role reaches can().
Granular Permissions#
Beyond CRUD: Expanding Actions#
As an application grows, simple CRUD does not cover all operations. New actions can be added to the array:
export const ACTIONS = [
'create',
'read',
'update',
'delete',
'publish',
'archive',
'invite-member',
'manage-settings',
] as const;
The Permission template literal type automatically expands. document:archive, project:invite-member, and project:manage-settings all become valid permission strings without any additional type definitions.
Department-Based Permission Helper#
When organizations have departments, a common pattern is checking both role permission AND department membership:
function canEditInDepartment(
role: Role | null, // resolved and validated upstream
session: { departmentId: string },
document: { project: { departmentId: string } }
): boolean {
// Step 1: Does the role have the permission? No role means no access
if (role === null || !can(role, 'document', 'update')) {
return false;
}
// Step 2: Is the user in the same department?
// Admin bypasses department restriction
if (role === 'admin') return true;
return session.departmentId === document.project.departmentId;
}
The helper takes the role already resolved, the same way canModifyDocument below does. In the project model that role comes from effectiveRole(). An org-wide model needs its own resolver that checks the stored role with isRole() and returns null for anything unknown.
Notice the department check is outside the can() function. RBAC’s can() only knows about roles and permissions. It has no concept of “which department” or “which specific resource.” This works for one or two contextual checks. But as these multiply (department, ownership, time-of-day, document status), the helper functions proliferate. We are back to the same problem.
Ownership-Based Permission Helper#
function canModifyDocument(
role: Role | null, // project-scoped role from effectiveRole()
userId: string,
document: { authorId: string }
): boolean {
// The role grant comes first; ownership alone grants nothing
if (role === null || !can(role, 'document', 'update')) return false;
// Ownership limits authors to their own documents
return role !== 'author' || document.authorId === userId;
}
Again, the ownership check is outside RBAC, and it joins the role check with AND. An OR fallback (“authors can always edit their own”) would let anyone who owns a document edit it through ownership alone: a member demoted to viewer, or a former member whose old documents are still in the project. The can() function cannot express “only your own documents.” This is by design: RBAC maps roles to permissions and nothing else.
Separation of Duty#
Constrained RBAC covers rules where the person who checks the work is not the person who did it. The example adopts a review rule that Post 102 did not have: whoever wrote a document does not publish it. Editors can both create and publish, so the role map alone lets an editor publish their own draft.
// lib/permissions.ts (continued)
export function canPublishDocument(
session: { userId: string; role: string },
document: {
authorId: string;
project: { ownerId: string; members: ProjectMember[] };
}
): boolean {
const role = effectiveRole(session, document.project);
if (role === null || !can(role, 'document', 'publish')) return false;
// Separation of duty: whoever wrote the document does not publish it
return document.authorId !== session.userId;
}
The NIST model states separation of duty between roles: one user may not hold two roles that check each other. That version fits the role map, for example as a check that rejects a role assignment creating such a pair. The per-document rule above compares authorId with the user, so it needs a resource attribute. It sits next to ownership, at the edge of what RBAC can express.
UI and Backend Synchronization#
The Shared Permission Module#
The key insight: lib/permissions.ts has no 'server-only' import. It contains no database access, no session handling, no server-specific APIs. It is a pure TypeScript module with type definitions, a constant object, and pure functions.
This means it can be imported by:
- Service layer files (server-only): for authorization
- React Server Components: for conditional rendering
- React Client Components: for conditional rendering
- Middleware: for route-level checks
All four import the same file, so there is one source of truth and no duplication.
Server Component Usage#
Server Components can call verifySession() and use the same helpers as the service layer. The component receives the document with its project members; as a Server Component, it keeps that list on the server.
// components/document-actions.tsx
import { verifySession } from '@/lib/auth';
import {
can,
canEditDocument,
canPublishDocument,
effectiveRole,
} from '@/lib/permissions';
export async function DocumentActions({
document,
}: {
document: DocumentWithProject;
}) {
const session = await verifySession();
if (!session) return null;
const role = effectiveRole(session, document.project);
if (role === null) return null;
return (
<div>
{canEditDocument(session, document) && (
<EditButton documentId={document.id} />
)}
{can(role, 'document', 'delete') && (
<DeleteButton documentId={document.id} />
)}
{canPublishDocument(session, document) && (
<PublishButton documentId={document.id} />
)}
</div>
);
}
Compare to Post 102’s version:
// Post 102: a copy of the service rule, prone to drift
const canEdit =
session.role === 'admin' ||
document.viewerRole === 'owner' ||
document.viewerRole === 'editor' ||
(document.viewerRole === 'author' &&
document.authorId === session.userId);
// Post 103: the same helper the service layer enforces
const canEdit = canEditDocument(session, document);
The component and the service layer call the same canEditDocument(), which queries the same ROLE_PERMISSIONS object. If an editor gains delete permission, change it in one place. Both server and client reflect the change automatically.
Client Component with Passed Permissions#
Client Components cannot call verifySession(). The solution: resolve permissions on the server and pass them as props. A service method computes the booleans with the same helpers that guard the writes:
// lib/services/document-service.ts (continued)
export async function getDocumentPermissions(documentId: string) {
const session = await requireSession();
const document = await db.document.findUnique({
where: { id: documentId },
include: { project: { include: { members: true } } },
});
// Missing and not allowed look the same, as in Post 102
if (!document || !canAccessDocument(session, document)) {
throw new NotFoundError();
}
const role = effectiveRole(session, document.project);
return {
canEdit: canEditDocument(session, document),
canDelete: role !== null && can(role, 'document', 'delete'),
canPublish: canPublishDocument(session, document),
};
}
// Server Component parent
import { getDocumentPermissions } from '@/lib/services/document-service';
export async function DocumentPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const permissions = await getDocumentPermissions(id);
return <DocumentToolbar permissions={permissions} />;
}
// Client Component child
'use client';
interface ToolbarProps {
permissions: {
canEdit: boolean;
canDelete: boolean;
canPublish: boolean;
};
}
export function DocumentToolbar({ permissions }: ToolbarProps) {
return (
<div>
{permissions.canEdit && <EditButton />}
{permissions.canDelete && <DeleteButton />}
{permissions.canPublish && <PublishButton />}
</div>
);
}
The Client Component knows nothing about the permission system. It receives booleans and renders accordingly.
The PermissionGate Component#
For repeated permission checks in templates, a reusable wrapper reduces boilerplate:
// components/permission-gate.tsx
import { verifySession } from '@/lib/auth';
import {
can,
effectiveRole,
type Resource,
type Action,
} from '@/lib/permissions';
export async function PermissionGate({
project,
resource,
action,
children,
fallback = null,
}: {
project: {
ownerId: string;
members: { userId: string; role: string }[];
};
resource: Resource;
action: Action;
children: React.ReactNode;
fallback?: React.ReactNode;
}) {
const session = await verifySession();
if (!session) return fallback;
const role = effectiveRole(session, project);
if (role === null || !can(role, resource, action)) {
return fallback;
}
return children;
}
Usage:
<PermissionGate
project={document.project}
resource="document"
action="delete"
>
<DeleteButton documentId={document.id} />
</PermissionGate>
The gate covers rules that depend only on the role. Actions with an ownership or separation-of-duty rule go through canEditDocument() and canPublishDocument().
Warning
UI permission checks are a user experience feature and provide no security on their own. A hidden button can still be called via direct API request, so the service layer remains the security boundary. UI checks prevent users from seeing actions they cannot perform; the service layer prevents them from executing actions they cannot perform.
Shipping the Map to the Browser#
Importing lib/permissions.ts from a Client Component has a cost the server paths do not. Next.js pulls whatever a Client Component imports into the client bundle. ROLE_PERMISSIONS, the role names and the helper logic then become readable to anyone who opens the browser’s developer tools. The map is not a credential, and the service layer enforces it either way, so nothing breaks. It does publish the shape of the authorization model, including roles a regular user never sees.
The default is the boolean pattern from DocumentToolbar: compute decisions on the server and pass only the answers. The browser learns what this user can do on this page and nothing about other roles. Import the map into a Client Component only when the client must decide many things without a server round trip (a role switcher that previews the UI per role, for example), and only when every role name and permission in it can be public.
RBAC Limitations: When can() Is Not Enough#
Contextual Decisions#
can(role, 'document', 'update') answers a general question: “Can editors update documents?” But the real question is often: “Can this editor update this specific document?” The project-scoped role already answers whether the editor belongs to the document’s project. The rest depends on:
- Is the document locked for editing?
- Is the document in “review” status?
- Is the user the document’s author?
None of these can be expressed in the role-permission map. They require attributes of the user, the resource, and the environment.
// RBAC can answer this (given Bob's role in the project):
can('editor', 'document', 'update'); // true
// RBAC cannot answer this:
// "Can editor Bob update document XYZ right now?"
// Depends on: XYZ's status, XYZ's lock, XYZ's author
Permission Matrix Explosion#
As requirements grow, teams create increasingly specific permissions:
document:update: generaldocument:update-own: only your owndocument:update-in-department: only in your departmentdocument:update-draft: only draftsdocument:update-published: only published documents
The permission matrix explodes. This is the code-level equivalent of NIST’s “role explosion” problem. Instead of creating new roles for every edge case, we are creating new permission strings; the same problem in disguise.
Helper Function Proliferation#
To handle contextual checks alongside RBAC, helper functions multiply:
// These all exist alongside can()
canEditOwnDocument(session, document);
canEditInDepartment(role, session, document);
canPublishInReviewStatus(session, document);
canDeleteIfNotLocked(session, document);
canAccessDraftInProject(session, document, project);
Each is a custom if/else chain. The can() function handles the role check, but the contextual logic is still imperative code. We have improved from Post 102, but the contextual checks remain scattered.
When to Use RBAC vs. When to Move Beyond#
RBAC is the right tool when permissions depend primarily on the user’s role: “Admins can do everything”, “Editors can update and publish”, “Viewers can only read.” RBAC is the wrong tool when permissions depend on context: ownership, resource state, department scoping, or environmental conditions. Project membership is not on that list, because a project-scoped role covers it.
What’s Next#
Every contextual check (ownership, department scoping, document status) still lives outside RBAC as a separate helper function. As these multiply, the system loses the declarative clarity that RBAC provides.
In Post 104, we introduce Attribute-Based Access Control (ABAC). The can() function evolves to evaluate attributes of the user, the resource, and the environment through a policy engine. Ownership, department scoping, and resource state turn into policy rules that the engine evaluates.
// Preview -- full implementation in Post 104
// Instead of:
if (can(role, 'document', 'update')) {
// still need ownership check separately
}
// We'll use:
if (evaluate(session, 'update', document)) {
// ownership, department, status -- all in one policy
}
The service layer and the overall architecture stay as they are; only the decision engine inside the permission checks evolves.
References#
- NIST Role-Based Access Control (RBAC) Project (opens in new tab) - NIST’s foundational project page for RBAC, including the formal definition and the INCITS 359 standard references
- The NIST Model for Role-Based Access Control (Sandhu, Ferraiolo, Kuhn, 2000) (opens in new tab) - The seminal paper defining the four RBAC model levels: flat, hierarchical, constrained, and symmetric RBAC
- OWASP A01:2025 - Broken Access Control (opens in new tab) - Broken access control remains the top risk in the OWASP Top 10, reinforcing why structured permission systems are critical
- OWASP Authorization Cheat Sheet (opens in new tab) - Best practices for centralized authorization logic, deny by default, and the principle of least privilege
- TypeScript 4.9: The satisfies Operator (opens in new tab) - Official documentation for the
satisfiesoperator used in theROLE_PERMISSIONSpattern - TypeScript Template Literal Types (opens in new tab) - Official documentation for template literal types that power the
Permissiontype - RBAC vs ABAC vs ReBAC (Web Dev Simplified) (opens in new tab) - Practical comparison of three permission models in TypeScript with code examples
- Role Explosion: The Hidden Cost of RBAC (Permify) (opens in new tab) - Analysis of role explosion causes, maintenance impact, and solutions through fine-grained access control
- CASL - Isomorphic Authorization JavaScript Library (opens in new tab) - The library that inspired the
can()function pattern; isomorphic, TypeScript-native authorization - Next.js Authentication Guide (Official) (opens in new tab) - Official Next.js documentation covering the Data Access Layer pattern and server-only authorization
- Next.js: The Server and Client Boundary (Official) (opens in new tab) - Explains that whatever a Client Component imports is pulled into the client bundle, while data crosses the boundary only as serialized props
- Role-Based Access Control (Wikipedia) (opens in new tab) - Overview of RBAC history, sessions, role hierarchies, separation of duty, and the core, hierarchical and constrained levels of the NIST standard
Permission Systems that Scale
Part 3 of 6A comprehensive guide to building scalable permission systems in TypeScript and Next.js, progressing from naive checks through RBAC and ABAC to production-grade multi-tenant authorization.
All posts in this series
Related posts
Authentication vs authorization, common permission pitfalls, the fail-closed principle, and the goals every permission system should meet.
typescript · nextjs · authorization +2
Refactor scattered permission checks into a centralized service layer, add Next.js middleware guards, and build a defense-in-depth authorization architecture.
typescript · nextjs · authorization +2
Build an ABAC policy engine in TypeScript with the builder pattern, conditional permissions, and type-safe policy evaluation that replaces RBAC's limitations.
typescript · nextjs · authorization +2
Extend ABAC with environment-based rules, field-level read and write permissions, and automatic database query filtering that eliminates duplicate permission logic.
typescript · nextjs · authorization +2
Add multi-tenant isolation to your permission system, evaluate CASL as a library alternative, and use decision frameworks to choose the right authorization architecture.
typescript · nextjs · authorization +3