Keep routes, controllers, and PostgreSQL repositories separated
In a clean MVC Express structure, routes bind HTTP paths and middleware, controllers translate validated parameters into service calls and HTTP status codes, and services/repositories execute parameterized SQL queries against PostgreSQL.
Keeping HTTP objects (req and res) out of service functions makes transactional logic testable without spinning up an HTTP server and prevents accidental leakage of internal database errors to API clients.
Parameterized PostgreSQL service separated from Express HTTP transport
export async function listWorkspaceMembers(
db: Pool,
workspaceId: string,
limit = 25,
offset = 0,
) {
const { rows } = await db.query(
`SELECT id, email, role, created_at
FROM workspace_members
WHERE workspace_id = $1 AND deleted_at IS NULL
ORDER BY created_at DESC
LIMIT $2 OFFSET $3`,
[workspaceId, limit, offset],
);
return rows;
}Separate JWT authentication from role and tenant authorization
Authentication answers who made the request; authorization answers whether that user can act on the target workspace or resource. Keep JWT verification in one middleware and declarative role checks in a second requireRole(...roles) guard.
Whenever a route accepts a resource ID, scope the PostgreSQL WHERE clause by both resourceId and req.user.workspaceId so horizontal privilege escalation is impossible even if a caller guesses another tenant's UUID.
- Hash passwords with Bcrypt and never store plaintext or reversible secrets.
- Pair short-lived JWT access tokens with revocable session checks for admin deactivation flows.
- Return consistent 401 (unauthenticated) vs 403 (unauthorized) responses without leaking record existence.
References: Express.js Security Best Practices · OWASP Access Control Cheat Sheet · PostgreSQL Constraints Documentation
Enforce invariants in PostgreSQL and paginate every list route
Unique email constraints, foreign-key references, and NOT NULL rules belong in PostgreSQL migrations rather than only in JavaScript checks. When concurrent requests arrive, the database guarantees consistency.
For admin dashboards and session telemetry tables, enforce bounded LIMIT/OFFSET or cursor pagination alongside composite indexes on (workspace_id, created_at DESC) so list queries remain fast as tables grow.