Software Crafting

Implementing Role-Based Access Control (RBAC) from Scratch in Node.js, TypeScript, and PostgreSQL

BBadal SinghBackend Development14 min read19 Apr 2026Updated 2026-11-07
Translucent blue shield icons sit on glowing pedestals connected by orange and blue network lines across a dark background

TL;DR: Move away from fragile, hardcoded role checks by building a Role-Based Access Control (RBAC) system from scratch. This guide demonstrates how to design a normalized PostgreSQL schema with five core tables and implement a reusable Express.js middleware in TypeScript to enforce granular resource:action permissions.

Key Takeaways

  • Stop checking hardcoded user roles (e.g., req.user.role === 'admin') in route handlers and instead verify granular permissions to decouple access control from business logic.
  • Design a normalized PostgreSQL schema using five core tables (users, roles, permissions, role_permissions, and user_roles) to manage many-to-many access relationships.
  • Utilize PostgreSQL's gen_random_uuid() for primary keys and apply ON DELETE CASCADE on junction tables to maintain database integrity.
  • Adopt a strict resource:action naming convention (e.g., invoices:read, users:delete) to make routing code immediately understandable and auditable.
  • Extend the Express Request object with a global declaration file (declaration merging) that your tsconfig.json include already covers, so middleware can attach user and permission data with full typing.

You start your SaaS application with a simple authentication check. Upon login, you issue a JSON Web Token (JWT). In your route handlers, you write if (req.user.role === 'admin') { ... }. It works, for about three weeks.

Soon, the product manager requests a new "Billing Manager" role. They need access to invoices but shouldn't be able to delete user accounts. A week later, you need a "Support" role that can view user profiles but cannot change passwords. Your codebase quickly becomes a tangled mess of nested if statements, hardcoded arrays like ['admin', 'billing_manager', 'super_admin'], and duplicated authorization logic scattered across dozens of controllers.

This approach is fragile, difficult to audit, and prone to security vulnerabilities. If a developer forgets to add a specific role to a specific array on a specific route, unauthorized users gain access to restricted resources.

The solution is a Role-Based Access Control (RBAC) architecture decoupled from your business logic. Instead of checking who the user is (their role), your application code should only check what the user is allowed to do (their permissions). Roles simply become database entities that group those permissions together.

In this guide, you will learn how to architect a production-ready RBAC system from scratch using Node.js, TypeScript, and PostgreSQL. We will design the relational database schema, write the SQL queries to aggregate permissions, and build a reusable Express.js middleware to enforce access controls at the route level.

Designing the PostgreSQL Database Architecture

To build a scalable RBAC system, we need to completely decouple users, roles, and permissions. We can achieve this using a normalized relational database design that utilizes Many-to-Many relationships.

Our schema will consist of five core tables:

  1. users: Stores account information.
  2. roles: Stores role definitions (e.g., "Admin", "Editor").
  3. permissions: Stores distinct, granular actionable rights (e.g., "invoices:read", "users:delete").
  4. role_permissions: A junction table linking roles to their granted permissions.
  5. user_roles: A junction table linking users to their assigned roles.

Here is the SQL script to create this architecture:

-- 1. Create Core Tables (Assumes PostgreSQL 13+ for gen_random_uuid())
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE roles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(50) UNIQUE NOT NULL,
    description TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE permissions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(50) UNIQUE NOT NULL, -- e.g., 'invoices:read', 'users:write'
    description TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- 2. Create Junction Tables for Many-to-Many Relationships
CREATE TABLE role_permissions (
    role_id UUID REFERENCES roles(id) ON DELETE CASCADE,
    permission_id UUID REFERENCES permissions(id) ON DELETE CASCADE,
    PRIMARY KEY (role_id, permission_id)
);

CREATE TABLE user_roles (
    user_id UUID REFERENCES users(id) ON DELETE CASCADE,
    role_id UUID REFERENCES roles(id) ON DELETE CASCADE,
    PRIMARY KEY (user_id, role_id)
);

-- 3. Add Indexes for Query Performance
-- The composite primary keys already index user_roles(user_id, ...) and
-- role_permissions(role_id, ...). Add indexes on the second columns for
-- reverse lookups ("who has this role?") and fast ON DELETE CASCADE.
CREATE INDEX idx_user_roles_role_id ON user_roles(role_id);
CREATE INDEX idx_role_permissions_permission_id ON role_permissions(permission_id);

Production Note: Always establish a strict naming convention for permissions. A standard approach is resource:action (e.g., articles:create, articles:read, users:delete). This makes it immediately obvious what a permission controls when reading your routing code.

Setting Up the Node.js & TypeScript Project

Before writing the application logic, let's bootstrap a standard Node.js environment configured with TypeScript and the necessary PostgreSQL drivers.

# Initialize the project
npm init -y

# Install dependencies
npm install express pg jsonwebtoken dotenv cors
npm install -D typescript tsx @types/node @types/express @types/pg @types/jsonwebtoken @types/cors

Initialize and configure your TypeScript environment (tsconfig.json):

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "CommonJS",
    "rootDir": "./src",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"]
}

Note the include array. Because it covers everything in src, the declaration file we add shortly to extend the Express Request object is picked up automatically, so no typeRoots setting is needed. For local development, npx tsx watch src/index.ts runs the server; tsx does not type-check, so run npx tsc --noEmit in CI as well.

Set up your database connection pool using the pg package:

// src/db/index.ts
import { Pool } from 'pg';
import dotenv from 'dotenv';

dotenv.config();

export const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20, // Maximum number of connections in the pool
  idleTimeoutMillis: 30000,
});

// Helper that times queries; always pass user input through params ($1, $2, ...)
export const query = async (text: string, params?: unknown[]) => {
  const start = Date.now();
  const res = await pool.query(text, params);
  const duration = Date.now() - start;
  console.log('Executed query', { text, duration, rows: res.rowCount });
  return res;
};

Fetching User Permissions Dynamically

When a user makes a request to a protected endpoint, we need to determine what actions they are permitted to perform. There are two primary architectural patterns for handling this:

  1. Fat Tokens (JWT Payload): Embed an array of permission strings directly into the JWT upon login.
  2. Database/Cache Lookup: The JWT only contains the user_id. The server fetches the permissions from the database or a cache on every request.

Embedding permissions inside the JWT avoids a lookup, but it is a poor fit when permissions change often. If you revoke an administrator's access, their token still carries the old permissions until it expires, unless you add short expiry times or a revocation list.

Instead, we will fetch permissions dynamically. Here is the SQL query required to aggregate a user's permissions across all their assigned roles:

SELECT DISTINCT p.name AS permission_name
FROM permissions p
JOIN role_permissions rp ON p.id = rp.permission_id
JOIN user_roles ur ON rp.role_id = ur.role_id
WHERE ur.user_id = $1;

Let's wrap this logic inside a TypeScript service class:

// src/services/rbac.service.ts
import { query } from '../db';

interface PermissionRow {
  name: string;
}

export class RBACService {
  /**
   * Retrieves all unique permissions for a given user ID.
   */
  static async getUserPermissions(userId: string): Promise<string[]> {
    const sql = `
      SELECT DISTINCT p.name
      FROM permissions p
      JOIN role_permissions rp ON p.id = rp.permission_id
      JOIN user_roles ur ON rp.role_id = ur.role_id
      WHERE ur.user_id = $1;
    `;

    try {
      const result = await query(sql, [userId]);
      // Map the resulting rows into a flat array of strings
      return result.rows.map((row) => (row as PermissionRow).name);
    } catch (error) {
      console.error('Error fetching user permissions:', error);
      throw new Error('Database error while fetching permissions');
    }
  }
}

By utilizing DISTINCT, we ensure that if a user has two different roles that both grant the invoices:read permission, the resulting array only includes it once.

Extending the Express Request Object in TypeScript

To pass the user's ID and resolved permissions down to our route handlers, we must attach them to the req object. In TypeScript, the standard express.Request type doesn't recognize our custom properties. We need to use Declaration Merging to extend it.

Create a type definition file:

// src/types/express/index.d.ts
export {};

declare global {
  namespace Express {
    export interface Request {
      user?: {
        id: string;
        email: string;
      };
      permissions?: string[];
    }
  }
}

Now TypeScript accepts req.user = ... and req.permissions = [...] inside our middleware. Because this file is under src, the include setting in tsconfig.json already picks it up.

Building the Authentication and Authorization Middlewares

A scalable RBAC pipeline generally requires two separate middlewares executed sequentially:

  1. authenticate: Verifies the JWT and attaches the user_id to the request.
  2. requirePermissions: A factory function that takes an array of required permissions, fetches the user's actual capabilities, and compares them.

1. The Authentication Middleware

// src/middleware/auth.middleware.ts
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

interface JwtPayload {
  id: string;
  email: string;
}

export const authenticate = (req: Request, res: Response, next: NextFunction): void => {
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    res.status(401).json({ error: 'Unauthorized: No token provided' });
    return;
  }

  const token = authHeader.split(' ')[1];

  const secret = process.env.JWT_SECRET;
  if (!secret) {
    throw new Error('JWT_SECRET is not configured');
  }

  try {
    // Pin the accepted algorithm so a token cannot choose its own
    const decoded = jwt.verify(token, secret, { algorithms: ['HS256'] }) as JwtPayload;

    // Attach user payload to the request object
    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Unauthorized: Invalid or expired token' });
    return;
  }
};

2. The RBAC Middleware

Next, we build the core of our authorization system. This middleware is designed to accept an array of required permissions. It fetches the user's permissions and verifies that they possess all required capabilities.

// src/middleware/rbac.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { RBACService } from '../services/rbac.service';

/**
 * Middleware factory to enforce permission checks
 * @param requiredPermissions Array of permission strings required for the route
 */
export const requirePermissions = (requiredPermissions: string[]) => {
  return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.user) {
        res.status(401).json({ error: 'User not authenticated' });
        return;
      }

      // Fetch user's permissions from the database
      const userPermissions = await RBACService.getUserPermissions(req.user.id);

      // Attach to request object for potential use in downstream controllers
      req.permissions = userPermissions;

      // Ensure the user has EVERY permission required by the route
      const hasAllPermissions = requiredPermissions.every((permission) =>
        userPermissions.includes(permission),
      );

      if (!hasAllPermissions) {
        res.status(403).json({
          error: 'Forbidden: Insufficient permissions',
          required: requiredPermissions,
        });
        return;
      }

      next();
    } catch (error) {
      console.error('RBAC Middleware Error:', error);
      res.status(500).json({ error: 'Internal server error during authorization' });
      return;
    }
  };
};

Tip: In the middleware above, we used requiredPermissions.every(...). This means the user must possess all listed permissions. If you have use cases where a user needs permission A or permission B, you can create an alternative middleware that utilizes requiredPermissions.some(...).

Applying Permissions to Express Routes

With our architecture in place, securing our endpoints becomes declarative and easy to audit. Let's wire up a sample Express router for an invoicing service.

// src/routes/invoices.routes.ts
import { Router, Request, Response } from 'express';
import { authenticate } from '../middleware/auth.middleware';
import { requirePermissions } from '../middleware/rbac.middleware';

const router = Router();

// Enforce authentication on all routes within this router
router.use(authenticate);

// Users with 'invoices:read' can access this endpoint
router.get('/', requirePermissions(['invoices:read']), (req: Request, res: Response) => {
  res.json({ message: 'List of invoices returned' });
});

// Only users with 'invoices:create' can hit this endpoint
router.post('/', requirePermissions(['invoices:create']), (req: Request, res: Response) => {
  res.status(201).json({ message: 'Invoice created successfully' });
});

// Requires BOTH read and delete permissions simultaneously
router.delete(
  '/:id',
  requirePermissions(['invoices:read', 'invoices:delete']),
  (req: Request, res: Response) => {
    res.json({ message: `Invoice ${req.params.id} deleted` });
  },
);

export default router;

This is the main benefit of RBAC. The controller logic is unaware of "Roles." If the marketing team needs a new "Auditor" role that can only read invoices, you don't touch the codebase. You simply insert a new row into the roles table, link it to the invoices:read permission in role_permissions, and assign that role to the auditor in user_roles.

Scaling the Architecture: Caching Permissions with Redis

If you implement the code exactly as written above, your application will run a two-join permissions query on every single authenticated HTTP request. For a low-traffic internal tool, this is fine: with the primary keys and indexes above, PostgreSQL resolves it with index lookups, typically in a few milliseconds. Measure it with EXPLAIN ANALYZE on your own data.

However, on a high-traffic SaaS application, this adds a database round trip and load to every request. Adding a short-lived cache for authorization data is a standard step in backend and API development once that load shows up in your metrics.

Redis is a good fit here. On the first request after a cache miss, we fetch the user's permissions from PostgreSQL and cache the resulting array in Redis as a serialized JSON string.

Here is how you modify the RBACService to implement the "Cache-Aside" pattern:

// src/services/rbac.service.ts
import { query } from '../db';
import { createClient } from 'redis';

// Initialize Redis Client (connect it during your app's startup, before serving requests)
const redisClient = createClient({ url: process.env.REDIS_URL });
// node-redis requires an error listener; without one, errors crash the process
redisClient.on('error', (err) => console.error('Redis Client Error', err));
redisClient.connect().catch(console.error);

export class RBACService {
  static async getUserPermissions(userId: string): Promise<string[]> {
    const cacheKey = `user:${userId}:permissions`;

    try {
      // 1. Try to fetch from Redis Cache
      const cachedPermissions = await redisClient.get(cacheKey);

      if (cachedPermissions) {
        return JSON.parse(cachedPermissions);
      }

      // 2. If Cache Miss, fetch from PostgreSQL
      const sql = `
        SELECT DISTINCT p.name
        FROM permissions p
        JOIN role_permissions rp ON p.id = rp.permission_id
        JOIN user_roles ur ON rp.role_id = ur.role_id
        WHERE ur.user_id = $1;
      `;

      const result = await query(sql, [userId]);
      const permissions = result.rows.map((row) => (row as { name: string }).name);

      // 3. Save to Redis Cache with a Time-To-Live (TTL) of 15 minutes (900 seconds)
      await redisClient.set(cacheKey, JSON.stringify(permissions), { EX: 900 });

      return permissions;
    } catch (error) {
      console.error('Error in getUserPermissions:', error);
      throw error;
    }
  }

  /**
   * Call this whenever a user's roles change so the next request re-reads them.
   */
  static async invalidateUserPermissionsCache(userId: string): Promise<void> {
    await redisClient.del(`user:${userId}:permissions`);
  }
}

Now the permissions query runs at most once every 15 minutes per active user, plus after each invalidation. When an admin changes a user's roles, call RBACService.invalidateUserPermissionsCache(userId) so their next request sees the new permissions. When you change the permissions attached to a role, invalidate the cache for every user holding that role (the idx_user_roles_role_id index makes that lookup cheap). The 15-minute TTL is the upper bound on how long a missed invalidation can leave stale access in place, so choose it with that in mind.

Advanced Considerations: Moving to ABAC

RBAC covers many access rules well, but it runs out when requirements become context-sensitive.

For example: "A user can only delete an invoice IF they are the author of that specific invoice."

RBAC cannot solve this natively. The permission invoices:delete only establishes that they are generally allowed to delete invoices, not which specific invoices they own.

To solve this, you transition toward Attribute-Based Access Control (ABAC). This usually involves fetching the resource from the database inside the controller, and then explicitly checking ownership:

// Inside your controller
const invoiceResult = await query('SELECT * FROM invoices WHERE id = $1', [req.params.id]);
const invoice = invoiceResult.rows[0];

if (!invoice) {
  return res.status(404).json({ error: 'Invoice not found' });
}

// Combine RBAC (handled by middleware) with ABAC (handled in controller)
if (invoice.author_id !== req.user?.id && !req.permissions?.includes('invoices:delete_any')) {
  return res
    .status(403)
    .json({ error: 'You do not have permission to delete this specific resource' });
}

// Proceed with deletion...

By combining an RBAC middleware with context-aware ownership checks, you cover most SaaS authorization needs. If attribute rules multiply, consider a dedicated policy engine (such as Open Policy Agent or Cedar) rather than growing if statements in controllers. For tenant isolation on top of RBAC, see secure multi-tenant API isolation and authorization.

Sources

Need Help Shipping This?

Access control gets harder the moment you have more than one customer: tenants, roles, invitations, and audit trails all have to agree. If you are building a B2B SaaS product, we can help design a permission model that holds up in enterprise security reviews. You can also hire Node.js developers, or read how we handle secure JWT authentication with HttpOnly cookies.

Send us your brief

Frequently Asked Questions

Why use five separate tables instead of just adding a "role" column to the users table?

A single role column tends to push authorization logic into hardcoded if statements scattered across your controllers, and it limits each user to one role. A five-table normalized schema separates users, roles, and permissions, so your code checks what a user can do rather than who they are. That makes new roles a data change instead of a code change, and makes access easier to audit.

What is the best naming convention for RBAC permissions in the database?

A common convention is a resource:action format, such as invoices:read, articles:create, or users:delete. This strict naming convention makes it immediately obvious what specific rights a permission grants. It also keeps your routing and middleware code readable.

How do I handle TypeScript errors when adding the user payload to the Express Request object?

Extend the Express.Request interface in a declaration file that uses declare global { namespace Express { interface Request { ... } } }, and make sure the file is covered by the include setting in your tsconfig.json (for example src/**/*). If you run TypeScript with ts-node, note that it ignores include by default and needs its --files option to load such declaration files.

Won't querying the permission tables on every API request hurt application performance?

With the indexes in this guide the query uses index lookups, but running it on every request adds latency and load under heavy traffic. You can cache a user's aggregated permissions in an in-memory store like Redis with a short TTL and explicit invalidation. Alternatively, you can embed the permissions array directly into the JWT payload, provided you implement a strategy for token invalidation.

What if my application requires multi-tenant RBAC or Attribute-Based Access Control (ABAC)?

The schema in this guide is a foundational RBAC implementation. For multi-tenant SaaS, a common extension is adding a tenant_id to user_roles so a user can hold different roles in different organizations, and filtering every query by tenant. For attribute-based rules, keep ownership checks close to the data access code or move to a policy engine once the rules multiply.

About the author

Badal Singh

Co-founder of SoftwareCrafting

Badal Singh is the Co-founder of SoftwareCrafting in Delhi and writes technical guides about web and mobile development, backend security, cloud infrastructure, DevOps, and developer tooling.

Writes about Next.js, React, Node.js, PostgreSQL, React Native, Flutter.

View author profile

Last updated: 2026-11-07