Multi-tenant SaaS design
What you need to know
A multi-tenant SaaS application serves distinct organizations while enforcing tenant separation on every resource operation. A tenant slug in a Next.js route is a lookup hint, never proof of membership.
By the end, you can: model tenant-scoped data; test cross-tenant access.
A tenant-scoped progress query
SELECT lesson_id, percent, revisionFROM progressWHERE tenant_id = ? AND member_id = ? AND lesson_id = ?;Expected behavior: Bind all three parameters from the verified actor and validated lesson ID. Identical IDs in a different tenant cannot match.
How it works
Derive the actor from a verified session and confirm membership and permission for the chosen tenant. Apply the tenant predicate in SQL together with resource and owner or role predicates. The same lesson ID can legitimately appear in two tenants, so key lookups by the full identity. Prefer composite keys and foreign keys that prevent cross-tenant relations. For example, if lessons have PRIMARY KEY (tenant_id, id), a progress row should reference FOREIGN KEY (tenant_id, lesson_id) REFERENCES lessons(tenant_id, id), rather than referencing lesson_id alone. A foreign key verifies relational consistency, not whether the caller is allowed to act. Do not fetch a row by ID and then rely on a UI filter. Server Actions and Route Handlers can be invoked independently of layouts; they must enforce authorization themselves, ideally via a shared DAL. Do not serialize internal account data or another member's content. For this capstone private reads are request-specific and not placed in a shared persistent cache. For an explicitly tenant-public catalog a tenant-aware key can be appropriate, but membership checks cannot be skipped by a cache hit. Test both a different tenant with identical IDs and a same-tenant member with insufficient role. Return a consistent not-found policy when revealing existence would disclose private records; audit denials without logging private payloads.
Synthetic access cases
[ { "actor": "north/alex", "resource": "north/alex/intro", "allow": true }, { "actor": "north/beth", "resource": "north/alex/intro", "allow": false }, { "actor": "south/alex", "resource": "north/alex/intro", "allow": false }]Expected behavior: The policy checks both tenant and membership identity; matching a user ID string is insufficient.
Common mistake
A layout guard, Proxy redirect or client-side role check is not sufficient access enforcement. A cache tag also does not determine who is allowed to see its value.
Practice and verification
Run the capstone SQLite tests. Add a lesson with the same ID in a second tenant, try a cross-tenant update and verify both records remain unchanged. Document whether denial should reveal existence.
Scope: Proposed Next.js 16.x / React 19; App Router, Cache Components disabled unless noted. Framework and browser examples are staged, not executed. No exact patched dependency release or live deployment verified.