Multi-tenancy
Multi-tenancy
Section titled “Multi-tenancy”A multi-tenant application serves several organizations — schools, companies, workspaces — from one deployment. The same user can belong to more than one of them, with a different role in each, and says which one a request is for: a header, a subdomain, a path segment.
This guide assembles the pieces Veloce-TS provides for that shape into one setup. Every step below is exercised by a test in the framework’s own suite (tests/readme-recipes.test.ts).
Why the token’s role is not enough
Section titled “Why the token’s role is not enough”@Roles(['owner']) checks the roles claim of the access token. A token is issued once, at login, before the user has said which organization they want. So the claim can only hold a role — and if the guard trusts it, a user who is an owner of organization A passes @Roles(['owner']) on a request for organization B, where they are an ordinary member.
The role has to be resolved per request, from the membership in the organization that request names.
The setup
Section titled “The setup”import { Veloce, AuthPlugin, RBACPlugin, ForbiddenException, createParamDecorator, registerDrizzle,} from 'veloce-ts';import { sql } from 'drizzle-orm';
export interface Tenant { id: string; memberId: string; role: string;}
// Type the context variable once; `c.get('tenant')` is then typed everywheredeclare module 'hono' { interface ContextVariableMap { tenant: Tenant; }}
const app = new Veloce();
app.usePlugin(new AuthPlugin({ jwt: { secret: process.env.JWT_SECRET! }, userProvider,}));1. Resolve the tenant once per request
Section titled “1. Resolve the tenant once per request”app.use(async (c, next) => { const user = c.get('auth.user'); const orgId = c.req.header('X-Org-ID');
if (user && orgId) { const member = await findMembership(user.sub, orgId); if (!member) throw new ForbiddenException('Not a member of this organization'); c.set('tenant', { id: member.orgId, memberId: member.id, role: member.role }); }
await next();}, { phase: 'afterPlugins' });The afterPlugins phase is what makes auth.user available here; a plain app.use() runs before authentication. See Middleware › Phases.
The membership lookup is the only place the organization id from the request is trusted, and it is checked against the authenticated user. Everything downstream reads tenant from the context, never the header.
2. Take roles from the membership
Section titled “2. Take roles from the membership”app.usePlugin(new RBACPlugin({ roles: [ { name: 'owner', permissions: ['*'], level: 100, inherits: ['member'] }, { name: 'member', permissions: [], level: 10 }, ], resolveRoles: (c) => { const tenant = c.get('tenant'); if (!tenant) throw new ForbiddenException('X-Org-ID header required'); return [tenant.role]; },}));From here on @Roles(['owner']) means owner of the organization this request is for.
3. Hand the tenant to handlers as a parameter
Section titled “3. Hand the tenant to handlers as a parameter”export const CurrentTenant = createParamDecorator<Tenant>((c) => c.get('tenant'));@Controller('/projects')@Roles(['member'])class ProjectsController { constructor(@InjectDB() private db: DB) {}
@Get('/') list(@CurrentTenant() tenant: Tenant) { return this.db.select().from(projects).where(eq(projects.orgId, tenant.id)); }
@Post('/') @Roles(['owner']) create(@CurrentTenant() tenant: Tenant, @Body(NewProject) body: NewProject) { return this.db.insert(projects).values({ ...body, orgId: tenant.id }).returning(); }}No handler calls a “resolve tenant” helper, so none can forget to.
4. Rate-limit by caller, not by tenant header
Section titled “4. Rate-limit by caller, not by tenant header”app.useRateLimit({ windowMs: 60_000, max: 300, keyBy: 'user-or-ip', trustedProxyHops: 1 });Keying the limiter on the organization header is a common mistake: the header is client-supplied, so a caller can dodge the limit with a new value per request, or exhaust another organization’s quota by sending its id. See Middleware › Rate limiting.
5. Let the database enforce isolation too
Section titled “5. Let the database enforce isolation too”Every query above filters by orgId. A second barrier means one forgotten filter is not a data leak. With PostgreSQL row-level security, policies compare each row’s tenant to a per-transaction setting — and onBegin is where that setting gets written:
registerDrizzle(app, db, { transactionPerRequest: (c) => c.req.method !== 'GET', onBegin: async (tx, c) => { const tenant = c?.get('tenant'); if (tenant) { await tx.execute(sql`select set_config('app.tenant_id', ${tenant.id}, true)`); } },});alter table projects enable row level security;alter table projects force row level security;
create policy tenant_isolation on projects using (org_id = current_setting('app.tenant_id', true)::uuid) with check (org_id = current_setting('app.tenant_id', true)::uuid);Three details decide whether this actually protects anything:
- The setting must be written inside the transaction that runs the queries.
set_config(…, true)andSET LOCALonly last until the end of the current transaction; executed on their own, outside one, they have no effect on the queries that follow — which may not even run on the same pooled connection. - The application must not connect as a superuser or as the table owner without
FORCE. Both bypass row-level security entirely. - Order of registration.
registerDrizzleadds its ownafterPluginsmiddleware. Register it after the tenant middleware from step 1, so the tenant is known when the transaction begins.
onBegin also runs for transactions you open yourself with @Transactional() or runInTransaction() during a request. Reads outside any transaction do not get the setting: either wrap GET requests too (transactionPerRequest: true), or rely on the explicit filter for reads. See Transactions.
What a request looks like
Section titled “What a request looks like”| Request | Outcome |
|---|---|
| No token | 401 (deny by default) |
Token, no X-Org-ID | 403 — resolveRoles has no tenant |
| Token, organization the user does not belong to | 403 from the tenant middleware |
Member of the organization, route needs owner | 403 |
| Owner of organization A, request for A | Allowed |
| Owner of organization A, request for B where they are a member | Treated as a member of B |
WebSocket gateways
Section titled “WebSocket gateways”Gateways go through the same global middleware, so the tenant middleware from step 1 runs for an upgrade request that carries an Authorization header. Browsers cannot send one; with connection tickets the user is identified during the upgrade itself, so resolve the membership in authorizeUpgrade and keep it on the connection:
@WebSocket('/ws/org', { auth: true })class OrgGateway implements WebSocketGateway<{ orgId: string; role: string }> { async authorizeUpgrade(c: Context) { const orgId = c.req.query('org'); if (!orgId) return false; const member = await findMembership(c.get('auth.user')!.sub, orgId); return member ? { orgId: member.orgId, role: member.role } : false; }
@OnConnect() onConnect(conn: WebSocketConnection<{ orgId: string; role: string }>) { conn.join(`org:${conn.data.orgId}`); }}When a member is removed from an organization, close their sockets: plugin.getManager().disconnectUser(userId).
Testing it
Section titled “Testing it”The case that matters is the one a single-tenant test suite never exercises: one user in two organizations.
it('an owner of A is only a member in B', async () => { const alice = client.withToken(aliceToken);
const inA = await alice.post('/projects', { headers: { 'X-Org-ID': orgA }, json: { name: 'x' } }); const inB = await alice.post('/projects', { headers: { 'X-Org-ID': orgB }, json: { name: 'x' } });
expect(inA.ok).toBe(true); expect(inB.status).toBe(403);});Add the same check for every route whose access depends on the role, and one for an organization the user does not belong to at all.