Guide · November 26, 2026 · 3 min read
Multi-tenant SaaS with Django and Next.js: a practical guide
How to model tenants, resolve the active workspace, scope every query and switch workspaces safely in a Django REST Framework API with a Next.js frontend.
Multi-tenancy is the decision that is hardest to retrofit in a SaaS. Every table, query, cache key and background job has to know which customer it belongs to. This guide walks through a design that works well for B2B products built with Django REST Framework and Next.js — the same one SaaS Dock ships.
1. Choose logical isolation
There are three common models:
- Shared database, shared schema: every tenant-owned row has a
tenant_idforeign key. - Schema per tenant (for example with
django-tenants): one PostgreSQL schema per customer. - Database per tenant.
For an early-stage SaaS the first is almost always right. Migrations run once, connection pooling stays simple, and cross-tenant reporting is a normal query. The cost is discipline: forgetting a filter leaks data. The rest of this guide is about making that filter impossible to forget.
2. Model tenants and memberships
class Tenant(BaseModelUUID):
name = models.CharField(max_length=150)
language = models.CharField(max_length=10, default="en") # emails, async jobs
class TenantMember(BaseModelUUID):
class Status(models.TextChoices):
PENDING = "pending"
ACTIVE = "active"
INACTIVE = "inactive"
EXPIRED = "expired"
tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, related_name="members")
user = models.ForeignKey("users.User", on_delete=models.CASCADE, related_name="tenant_memberships")
role = models.ForeignKey("tenants.Role", on_delete=models.PROTECT)
status = models.CharField(max_length=10, choices=Status.choices)
A user can belong to several tenants; the membership carries the role and its status. Invitations are memberships in PENDING status, which keeps “who can see this workspace” in one table.
3. Resolve the tenant once per request
A middleware resolves the active tenant and the caller’s membership in a single query and attaches both to the request:
- The
x-tenant-idheader, only if the user has an active membership in that tenant. - Otherwise the user’s last-used tenant.
- Otherwise their first active membership.
Two details matter more than they look:
- Middleware errors become 500s. DRF’s exception handler never sees an exception raised inside a Django middleware. A malformed header must be treated as “no tenant”, not raise
ValidationErrorwhen it is parsed as a UUID. - Load the role with the membership (
select_related("role")), because every permission check on the request will need it.
4. Scope every queryset automatically
Rather than trusting each view to filter, put the filter in a mixin that every tenant-owned ViewSet uses:
class TenantViewSetMixin:
def get_queryset(self):
return super().get_queryset().filter(tenant=self.request.tenant)
def perform_create(self, serializer):
serializer.save(tenant=self.request.tenant)
The tenant comes from the request, never from the request body, so a client cannot write into someone else’s workspace by sending a different tenant field. Lookups by primary key go through the same filtered queryset, so /projects/<id>/ for another tenant’s project is a 404, not a 403 that confirms it exists.
Background jobs need the same care: pass the tenant id explicitly to Celery tasks and re-scope inside the task.
5. Permissions per tenant
Being a member is not enough; the role decides what the member may do. Permission strings shaped app.resource.action with wildcards make this manageable — see role-based permissions with wildcards in DRF. Two checks are not permission strings at all: whether you may edit another member (compare role levels, so an admin cannot demote the owner) and whether you may assign a role above your own.
6. The frontend: carry the tenant, refresh on switch
In Next.js, an authenticated HTTP client adds the bearer token and x-tenant-id to every request. Where the tenant id comes from matters:
- If it lives in the session token (NextAuth’s JWT), that token is frozen at login. Switching workspace must update the session (
session.update()), or the API keeps serving the previous tenant to every request. - Cached queries must be keyed or cleared per tenant, or the new workspace briefly shows the old one’s data.
7. Plan limits belong to the tenant
In B2B SaaS the subscription belongs to the workspace, not the user. Seats, projects or any numeric limit are checked against the tenant’s plan on the API (403 with a clear code), and the frontend reads the same limits to disable the invite button before the user hits the wall.
Checklist
- Tenant FK on every tenant-owned model, indexed with the columns you filter by
- Tenant resolved in middleware, header validated against an active membership
- Querysets scoped in one mixin; tenant stamped server-side on create
- Celery tasks receive and re-scope by tenant id
- Workspace switch updates the session and clears cached queries
- Limits enforced on the API, mirrored in the UI
- Tests that try to read and write across tenants and expect 404
Skip the build
SaaS Dock implements all of the above — tenant middleware, scoped ViewSets, invitations, ownership transfer, roles with wildcard permissions, per-tenant plan limits and the Next.js side that carries and switches the tenant — with cross-tenant tests in the suite. See what’s inside.
Frequently asked questions
- Shared database or schema-per-tenant for a new SaaS?
- Start with a shared database and a tenant foreign key on every tenant-owned table. It is simpler to migrate, back up and query across tenants for analytics. Schema- or database-per-tenant earns its operational cost only with strict regulatory isolation or thousands of very large tenants.
- How does the frontend tell the API which workspace to use?
- Send the active tenant id in a header such as x-tenant-id on every request, and have the API validate it against an active membership before using it. Never trust the header on its own.
Keep reading
- Role-based permissions with wildcards in Django REST FrameworkDesign per-tenant RBAC for a Django SaaS: app.resource.action permission strings, wildcards, per-member overrides, role levels and keeping the Next.js UI in sync.
- NextAuth + Django JWT: refresh tokens without session leaksHow to store Django REST Framework JWTs in NextAuth, refresh them safely from server and client, avoid handing one user another user's tokens, and sign out cleanly.
- Django + Next.js vs a Next.js-only SaaS boilerplateWhen a Python API behind Next.js beats a JavaScript-only starter like ShipFast, Supastarter or MakerKit — and when it does not. An honest architecture comparison.