Use Next JS Multi Tenant Web Application with PostgreSQL

One shared PostgreSQL database is a practical starting point for many SaaS products. A shared schema keeps migrations and day-to-day operations in one place, while tenantId scopes each customer’s records.
Use Next JS Multi Tenant Web Application with PostgreSQL
Two customers can use the same Next JS Multi Tenant Web Application with PostgreSQL, but neither should see the other’s records. A tenant is a customer or organization whose records must remain separate from those of other customers. Your build must solve two problems: identifying the tenant for each request and isolating its data.

This example uses a shared schema and subdomains, such as acme.yourdomain.com. A URL can help identify a tenant, but a URL alone does not secure data. Server-side checks and database access rules must protect every record.
You will shape the database, route requests, verify access, and test the safeguards before launch. That gives your SaaS product a practical starting point without hiding the security work inside routing code. The first decision is where tenant data lives.
Key Takeaways
- Choose a data boundary before building tenant-owned models.
- Give each tenant-owned record a tenantId foreign key.
- Resolve a request’s slug on the server and verify membership.
- Include the verified tenantId in every business-data query.
- Use PostgreSQL Row-Level Security as an additional safeguard.
- Test two tenants through the same production-like pooler.
Which PostgreSQL Tenant-Isolation Strategy Fits Your SaaS?
Start with a shared schema unless a clear customer or compliance requirement calls for stronger physical separation. For many early-stage multi-tenant saas products, shared-schema storage is the simplest architecture to operate, and PostgreSQL Row-Level Security (RLS) adds enforcement without creating a fourth storage layout.
Each strategy draws the data boundary differently, so compare operational needs as well as security goals. A shared database can serve many tenants, but the application must consistently scope records. Schema-per-tenant and database-per-tenant add boundaries at the cost of more work.
Start with a shared schema unless a clear customer or compliance requirement calls for stronger physical separation. RLS is an added enforcement layer, not a separate storage layout.
| Strategy | Data boundary | Main advantage | Main tradeoff and fit |
|---|---|---|---|
| Shared schema with tenant_id | Tenant key on each owned row | One schema and migration path | Requires scoped queries; practical default |
| Schema per tenant | Separate PostgreSQL schema | Separate tables by tenant | Switch search_path; catalog size can grow |
| Database per tenant | Separate database | Distinct database boundary | Heavier operations and migrations |
A shared-schema design is a common default for new products because one deployment can manage a common set of tables. A rough planning range of 100-10,000 tenants can help frame early decisions, but it is not a capacity guarantee. Workload, queries, and database resources affect actual limits.
Schema-per-tenant designs require switching PostgreSQL search_path for each tenant. As tenant count grows, the database catalog can become larger to manage. Database-per-tenant offers a separate database boundary, which may suit a compliance or enterprise requirement, but each database adds connection, backup, and migration work.
Choose the least complex boundary that meets your customers’ requirements today. If a contract calls for separate databases or tenant-specific restore procedures, plan for that operational cost before promising the design. Next, make the ownership relationship explicit in your models.
How Should You Model Tenants and Their Data in Prisma?
Use a Project row as a concrete example: without a tenant key, the database cannot tell which organization owns it. In a shared schema, tenantId ties each tenant-owned record to its Organization, and every business row that belongs to a tenant needs that key.
Give Each Tenant-Owned Record a Tenant Key
Model Organization as the tenant’s organization record and Project as a business record owned by it. A compact Prisma-style outline is: Organization has id, slug, name, and projects; Project has id, tenantId, createdAt, title, and organization. Add tenantId as a required relation to Organization.
For example, the Project model can declare tenantId as an Int, then relate it to Organization through tenantId and Organization’s id. Every tenant-owned model, such as Project, Document, or Invoice, should carry the same required ownership key. This makes ownership visible in the schema and available to queries.
Add Relations, Uniqueness Rules, and Useful Indexes
Use a unique slug on Organization for stable tenant lookup. Add tenant-scoped uniqueness where names only need to be unique inside one organization, such as a project name. A composite unique constraint on tenantId and name allows two organizations to use the same project name.
Relate each owned model back to Organization, and add an index on tenantId and createdAt. That composite index supports queries for one tenant’s recent records, such as a project feed sorted by creation time. Indexes should match queries your application actually runs.
A slug identifies the Organization during lookup, but it does not replace tenantId on business rows. In an example portfolio, JSON template configuration can control optional display sections. That configuration changes presentation, not ownership; Projects and other business data still need explicit tenant relationships.
With ownership and query support represented in Prisma, prepare PostgreSQL and a repeatable migration workflow.
How Do You Set Up PostgreSQL and Run Safe Migrations?
Start by confirming that the application can connect to the intended PostgreSQL database before generating models or migrations. Put the connection string in a DATABASE_URL environment variable, and keep separate values for development and production so a local command cannot target live data by mistake.
Define the Prisma datasource and models, then create one reusable Prisma Client instance for the application. In development, the generated client code gives your application typed access to the schema. Reuse the instance instead of creating a new client for every request.
Configure the Database Connection and Prisma Client
Store DATABASE_URL in the environment rather than writing credentials into source code. Configure Prisma to read that value, and generate the Prisma Client after model changes. In a development server, a shared client instance avoids unnecessary database connections during repeated reloads.
Create and Apply Migrations Deliberately
Create a migration during development to turn model changes into reviewable SQL. Inspect the migration before applying it locally. Production should apply migrations that have been committed and reviewed, not create new migration files as part of a live request.
- Set DATABASE_URL for the intended database.
- Define the Prisma datasource and tenant-owned models.
- Generate the Prisma Client from the schema.
- Create and inspect a development migration.
- Apply committed migrations during deployment.
Keep the migration history with the codebase so each environment can apply the same schema changes in order. Do not edit production tables manually or run development reset commands against production. Those shortcuts can leave the database out of sync with the application code.
Once the schema is in place, decide how each incoming hostname identifies its tenant.
How Do You Build a Next JS Multi Tenant Web Application with PostgreSQL?
A request to acme.example.com can be served internally by the same Next.js application as the main site. In a subdomain setup, a Next.js proxy or middleware reads the host, finds a candidate slug, and rewrites the request internally. The browser can keep its original URL while the application serves a tenant route.
In development, name.localhost:3000 can resolve to a tenant; in production, name.yourdomain.com can do the same. A rewrite can direct the request to /tenant/[slug] without changing the visible address. Treat localhost separately because its host format differs from a production domain.
| Resolution method | Example URL | Main consideration |
|---|---|---|
| Subdomain routing | acme.example.com | Parse the host and map its label |
| Path routing | example.com/acme | Read the tenant slug from the path |
| Custom domain | acme-site.net | Map a verified hostname to a tenant |
Build the host parser to separate the tenant label from your base domain. Exclude framework assets from the middleware matcher so image, script, and stylesheet requests do not enter tenant routing. A rewrite to /tenant/[slug] can route the request internally, while preserving the URL shown in the browser.
Next.js file naming and routing conventions can vary by version, so follow the convention used by your installed version. Keep host parsing in a small server-side unit that you can test with production and localhost examples. This routing step finds a candidate tenant; it does not prove the visitor may access that tenant’s private data.
The phrase Next JS Multi Tenant Web Application with PostgreSQL describes the whole path, not just a hostname rewrite. Pass the resolved slug into trusted server-side logic rather than treating a request header as proof of identity.
How Does Each Request Get a Trusted Tenant Context?
A URL naming acme identifies a candidate, while a server-verified lookup confirms which Organization acme represents. The server resolves the slug to an Organization ID, then checks user membership when a route requires sign-in. That verified result is the tenant context, and client-supplied tenant IDs are not trusted evidence.
A hostname can be altered, and a request can carry forged values. Treat parsing, authentication, and membership as separate checks. A public page may allow anonymous access to published content, while editing or account management still requires an authenticated user with the right role.
Resolve the Slug to a Tenant Record on the Server
Use the host parser to obtain a candidate slug, then look up the Organization on the server. If no record matches, return a not-found response rather than guessing from a header or rendering another tenant’s page. The Organization ID, not the raw hostname, becomes the tenant context.
Verify the Signed-In User Belongs to That Tenant
For protected routes, authenticate the user and check a membership record that links the user to the Organization. Check the role too: membership alone may not authorize administrative actions. Keep public content rules distinct from rules for private records and management operations.
- Parse the host and extract a candidate slug.
- Look up the slug and Organization on the server.
- Authenticate the user when the route requires sign-in.
- Verify membership and the required role.
- Pass the verified tenant ID to the data layer.
Never accept tenantId from a form, query parameter, or untrusted client header. A malicious user could change that value to target another organization. Derive the ID from the server-side lookup and membership checks instead.
Once the request has a verified tenant ID, make it impossible for ordinary data access to omit that ID.
How Do You Keep Every Prisma Query Tenant-Scoped?
No business-data query runs without the verified tenant ID. A Prisma read should include a condition such as where: { tenantId: currentTenantId }, with the value coming from the verified tenant context. Make tenant-aware data helpers required, not optional, so callers cannot quietly skip the boundary.
A repository function can accept the tenant ID as a required argument and build the filter internally. Avoid helpers that accept an optional tenant filter, then let each route decide whether to add it. The rule should apply consistently across the codebase, not depend on developer memory.

Put Tenant Filtering in Required Data-Access Helpers
For a list of projects, use a findMany query with where: { tenantId: currentTenantId }. Apply the same boundary to detail reads, counts, and aggregates. A slug filter alone is not enough when the underlying business record needs an ownership key.
Scope Writes and Related Records Too
For updates and deletes, constrain both the record ID and tenantId. This prevents a guessed ID from changing another tenant’s record. Creates must assign the verified tenantId on the server, rather than trusting a value sent in the request body.
Nested relation queries and writes need the same boundary. A Project loaded for one tenant should not pull related data that belongs to another. Validate related record ownership before connecting it, and keep the tenant ID consistent through the full write operation.
- Reads: check list, detail, and nested relation results.
- Creates: assign the verified tenantId on the server.
- Updates: constrain both record ID and tenantId.
- Deletes: constrain both record ID and tenantId.
- Counts or aggregates: apply the tenantId condition.
Application filters reduce mistakes, and PostgreSQL can add another enforcement layer underneath them.
When Should PostgreSQL RLS Enforce Isolation?
A forgotten tenant filter is the concrete mistake PostgreSQL Row-Level Security (RLS) can catch. Enable RLS on tenant-owned tables and create a policy that compares each row’s tenantId with a transaction-local setting. The database checks the boundary itself, even if application code misses a filter.
The application sets the verified tenant ID and runs the protected query inside the same transaction. If the tenant context is absent, the policy should deny access rather than expose rows. RLS is defense in depth, not a replacement for authentication or authorization.
Make PostgreSQL Reject Cross-Tenant Rows
Apply a policy to each tenant-owned table that restricts visible and writable rows to the current tenant context. Policies should cover the operations your application uses, including reads and writes. Test expected access and denied access using the application’s real database role.
That database role must not bypass RLS. PostgreSQL table owners can also have different RLS behavior, so configure ownership deliberately. Use FORCE ROW LEVEL SECURITY where appropriate, and confirm the role used by the application cannot sidestep the policy.
Set Tenant Context Inside the Query Transaction
Set the tenant value locally for a transaction, then run the protected Prisma query within that same transaction. Do not set context in one transaction and assume a later query will inherit it. When context is missing, design the policy and application path to fail closed.
RLS limits the damage from a missed application filter, but it does not tell you whether a user is signed in or belongs to the Organization. Keep authentication and authorization checks in the server layer, then pass the verified tenant ID down to PostgreSQL.
The transaction boundary matters, especially when PostgreSQL connections are pooled.
What Does Connection Pooling Change for Tenant Isolation?
Two consecutive requests from different tenants can reuse pooled database connections, so tenant context must not carry over. With connection pooling, set context for the protected transaction rather than assuming a connection belongs to one tenant. Keep the tenant setting and its query inside the same transaction.
A session-level SET followed by a separate query is unsafe with transaction pooling. PgBouncer transaction pooling can reset session state between transactions, leaving the later query without the expected tenant value. Session pooling retains connection state, which creates a different risk: one request’s value may reach another.
| Pool mode | Session-state behavior | Tenant-context pattern | Main risk |
|---|---|---|---|
| Direct or session pooling | State can remain on a connection | Set context and clean it reliably | Tenant value leaks to a later request |
| Transaction pooling | State can reset between transactions | Set locally and query in one transaction | Separate query loses its context |
Use a transaction-local setting, then run the protected query within the same Prisma transaction. That keeps the setting attached to the transaction that needs it. Test this behavior through the actual production pooler, not only through a direct local connection.
Session pooling still requires reliable cleanup between tenants because a connection may serve more than one request. Having addressed the pool, assemble the create-and-render flow and verify it end to end.
How Do Signup and Tenant Pages Work End to End?
A new customer should receive a tenant URL only after the database transaction that creates the account succeeds. Validate the signup request, create an Organization and its initial user membership, and generate a unique slug. Handle slug collisions by catching the uniqueness conflict and requesting or generating another valid value.
A simple slug made by lowercasing a name and replacing spaces with hyphens can collide or create invalid host labels. Names may repeat, include punctuation, or contain characters unsuitable for a hostname. Check the final slug against the database constraint rather than assuming a conversion guarantees uniqueness.

Create a Tenant Safely During Signup
Write the Organization and initial membership in one transaction so a partial signup does not leave an ownerless tenant. Validate user input before saving it, and only return the tenant URL after the transaction commits. The URL can use the slug, but later access still needs server-side checks.
Render the Tenant’s Public Page from Server Data
Resolve the slug to an Organization on the server, then fetch page data using the verified tenant ID. Return a not-found response for an unknown slug. For a public page, metadata can use the tenant name and a short bio, while published content remains scoped to that tenant.
A template may store JSON configuration for optional sections such as hero, skills, projects, or contact. Render only the sections enabled for that tenant. Keep content records tenant-owned and query them with the verified ID; template settings control display, not access to records.
Keep public rendering separate from management actions. Anonymous visitors may read approved public content, while editing remains limited to authenticated members with suitable roles. A complete flow is useful only if tests prove one tenant cannot retrieve another tenant’s records.
How Can You Prove Tenants Cannot See Each Other’s Data?
Set up two organizations with deliberately similar records so an accidental unscoped query is easy to detect. Give both tenants a project with the same title, then check which row each account can reach. Similar test data makes a mistaken match harder to overlook.
Test application filters and RLS using the actual application database role. A privileged development role may bypass protections that the deployed role must follow. Run the checks through the same access path and pooler used in production, especially when RLS depends on transaction context.
Test both application filters and RLS with the real application role. A local test that bypasses the production pooler cannot prove pooled tenant context works.
Test Cross-Tenant Reads and Writes
Sign in as tenant A and try to read, update, delete, and count tenant B’s records. Repeat through direct URLs, nested relations, and API requests. A blocked page alone is not enough if an API response or aggregate still exposes another tenant’s data.
- Cross-tenant read: tenant A cannot retrieve tenant B’s record.
- Cross-tenant write: tenant A cannot change or delete tenant B’s row.
- Forged tenant header or ID: a client value cannot switch context.
- Unknown slug: an unmatched host does not show another tenant.
- Missing RLS context: PostgreSQL denies access to protected rows.
Include counts, aggregates, and nested relations in the test suite. Confirm that a record ID from another tenant does not become a valid update target. Also test anonymous requests to public pages separately from protected management routes.
Check Production Configuration Before Launch
Check production host parsing, HTTPS, and trusted proxy behavior. Confirm secrets are supplied securely, committed migrations are applied, and the pooler mode matches the transaction strategy. Make sure errors reveal no private data or database details to visitors.
Local tests without the production pooler do not validate pooled RLS behavior. Run the suite against the production-like database setup and application role. After the isolation tests pass, decide which tenant-specific features belong in the next stage.
What Should Change as Your SaaS Adds Tenants?
Change the architecture in response to a customer requirement, not as a feature checklist on day one. Add team roles when users need different access, and connect billing systems such as Stripe to the tenant Organization, not an individual tenant URL. Organization-level billing keeps subscriptions tied to the customer account.
Custom domains, tenant-specific backup or restore needs, and compliance requirements can signal that the current approach needs review. A large or compliance-sensitive tenant may justify a dedicated database, but plan migration and ongoing operations first. No tenant count alone guarantees a particular performance or scale limit.
Keep the shared setup until a real need makes its extra complexity worthwhile. Then assess what the customer requires, what the team can operate, and how existing records will move safely. Narrow the immediate next step to the requirement the first customers actually need.
Conclusion
Tenant separation depends on trusted request resolution and enforced data access. Give every request a verified tenant context, and give every tenant-owned query an explicit boundary. Both controls matter; PostgreSQL Row-Level Security and transaction-aware pooling add safeguards when application code or connection reuse goes wrong.
Do not rely on a subdomain as the security boundary. Resolve it on the server, verify access, and carry the resulting tenant ID into database operations. Keep the database role and transaction setup aligned with the protections you expect RLS to enforce.
Create two test tenants with similar records, then run the cross-tenant test suite before inviting customers. Run it against the production-like database setup, including the real application role and pooler. Make that the immediate launch check.
FAQ
Should I use one PostgreSQL database for every tenant?
Yes, one shared PostgreSQL database is a practical starting point for many SaaS products. A shared schema keeps migrations and day-to-day operations in one place, while tenantId scopes each customer’s records. Choose separate schemas or databases when customization, compliance, backup, or isolation requirements justify their added operational work. Review the boundary again when a concrete customer need changes.
Is a subdomain enough to identify a tenant securely?
No, a subdomain identifies only a candidate tenant. Server-side code must look up the slug, authenticate the user when needed, and check membership and role before granting access. Do not trust a client header or URL as proof. Public pages can allow anonymous reads of approved content, but private records and management actions still need their own authorization rules.
Do I need PostgreSQL RLS if every Prisma query has a tenantId filter?
RLS is not a replacement for tenantId filters, but it provides a database-level backstop against a forgotten filter. Use both for sensitive tenant data when the application role cannot bypass RLS and tenant context is set correctly for each transaction. Test the policy with the real application role, since a privileged role may behave differently.
Can I set the tenant ID once when a pooled connection opens?
No, setting it once is not safe with transaction pooling. PgBouncer can reset session state between transactions, so a later query may not have the tenant value. Set transaction-local tenant context and run the protected query in the same transaction. With session pooling, also ensure connection state is reliably cleared before another tenant’s request uses it.
How should I prevent two tenants from getting the same subdomain?
Enforce a unique constraint on the Organization slug and handle a database conflict during signup. Generate or request a different valid slug when another tenant already uses it. Lowercasing a name and replacing spaces with hyphens is not enough: names can collide or produce invalid host labels. Confirm the slug’s validity and uniqueness before returning the tenant URL.
Can a tenant use a custom domain instead of a subdomain?
Yes, a tenant can use a custom domain if the application maps that verified hostname to its Organization. Account for domain verification and trusted host-header handling so an untrusted request cannot claim another tenant’s domain. Keep authorization checks in server-side data access; a custom hostname identifies a candidate tenant but does not grant the visitor permission.
When should I move a tenant to its own database?
Consider a dedicated database when a specific customer’s compliance, backup and restore, or isolation requirements outweigh the added operational cost. Separate databases mean more connection management, migrations, and operational work. Plan how records will move, how deployments will apply changes, and how the new database will be monitored before committing to the split.
