Building Scalable SaaS Applications with Next.js and NestJS
An architecture guide covering authentication, multi-tenancy, background jobs and the path from MVP to scale.
A practical architecture guide to building a multi-tenant SaaS with Next.js and NestJS: how the two fit together, how to handle auth, databases, tenancy and background jobs, and what to avoid.
By Habib Ur RehmanSenior Full Stack Engineer & MVP Partner- Published
- 11 min read
Key takeaways
- Use Next.js for the product UI and public pages, and NestJS as a separate API that owns business logic, authentication and data access.
- Start as a modular monolith on PostgreSQL. Add queues, caching and extra services only when measurements justify them.
- For most B2B SaaS products, a shared database with a tenant_id column enforced by PostgreSQL row-level security is the best starting point for multi-tenancy.
- Move anything slow or unreliable (emails, reports, webhooks, AI calls) to background jobs with retries, so requests stay fast.
Short answer: a scalable SaaS architecture is one where adding customers mostly means adding capacity, not rewriting code. With Next.js and NestJS, that usually looks like a Next.js frontend that renders the UI, a NestJS API that owns the business rules, PostgreSQL for data with tenant isolation, and Redis-backed workers for slow jobs. The rest of this guide explains each decision, the trade-offs, and the mistakes I would avoid.
What is a scalable SaaS architecture?
Scalability is not just handling more traffic. For a SaaS product it means four things at once: the system handles more users and data, new features can be added without breaking old ones, one customer can never see another customer's data, and the team can still ship quickly as the codebase grows.
- Horizontal scalability: stateless application servers that can run as many copies as needed.
- Tenant isolation: a strict boundary between customers' data, enforced in more than one place.
- Asynchronous work: slow tasks run outside the request/response cycle.
- Operability: logs, metrics and alerts that explain what the system is doing.
Why use Next.js for a SaaS frontend?
A SaaS product has two very different surfaces: public pages that must rank in search (landing, pricing, docs, blog) and an authenticated app where speed and interactivity matter. Next.js handles both in one codebase.
Server Components keep the app fast
In the App Router, components are Server Components by default. They fetch data on the server and send HTML, which means less JavaScript in the browser. Add 'use client' only where you need state, effects or browser APIs. I cover this in detail in Next.js App Router patterns.
Marketing pages and the product share one stack
Server-rendered pricing and landing pages give crawlers complete HTML, while the logged-in dashboard can use client-side interactivity. One design system, one deployment pipeline and one set of TypeScript types serve both.
Why use NestJS for the backend?
NestJS is an opinionated Node.js framework built around modules, dependency injection and decorators. That structure is exactly what a growing SaaS backend needs.
- Modules group related code and make boundaries explicit, which is the foundation of a modular monolith.
- Dependency injection makes services easy to test and swap.
- Guards, pipes and interceptors give you consistent places for authentication, validation and logging.
- First-class TypeScript keeps contracts between layers checked at compile time.
A reference architecture
The diagram below shows the setup I would start from. The browser talks to Next.js. Next.js calls the NestJS API. The API reads and writes PostgreSQL and pushes slow work onto a Redis-backed queue that separate workers process.
Every box except PostgreSQL and Redis is stateless, so each can be scaled by running more copies. Configuration comes from environment variables, in line with the Twelve-Factor App principles.
How should the frontend and backend communicate?
Keep the API as the single place that enforces rules. Next.js Server Components can call it directly from the server, which keeps tokens out of the browser and avoids extra round trips. Client Components call it through route handlers or directly for interactive features.
import { cookies } from "next/headers"
export default async function ProjectsPage() {
const token = (await cookies()).get("session")?.value
// Per-user data: do not cache across users.
const res = await fetch(process.env.API_URL + "/projects", {
headers: { Authorization: "Bearer " + token },
cache: "no-store",
})
if (!res.ok) throw new Error("Failed to load projects")
const projects: { id: string; name: string }[] = await res.json()
return (
<ul>
{projects.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
)
}REST, GraphQL or tRPC?
| Approach | Best for | Trade-offs | Fit with NestJS |
|---|---|---|---|
| REST + OpenAPI | Simple CRUD, public APIs, mobile and third-party clients | Possible over- or under-fetching; versioning needs discipline | Excellent: controllers and @nestjs/swagger |
| GraphQL | Many clients with very different data needs | More complexity: caching, N+1 queries, query cost limits | Good: code-first and schema-first modes |
| tRPC | One TypeScript monorepo with a web-only client | Couples client and server; weaker for public or mobile APIs | Possible with adapters; not first-class |
For most SaaS products, REST with an OpenAPI spec is the safest default. It works with every client, including a future React Native app, and the generated spec can produce typed clients.
How should authentication and authorization work?
Treat authentication (who are you?) and authorization (what may you do?) as separate concerns. A common pattern is to issue a short-lived access token that carries the user id, tenant id and role, store the session in an HTTP-only cookie on the Next.js side, and verify the token in a NestJS guard on every request.
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common"
import { JwtService } from "@nestjs/jwt"
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(private readonly jwt: JwtService) {}
async canActivate(ctx: ExecutionContext): Promise<boolean> {
const req = ctx.switchToHttp().getRequest()
const token = req.headers.authorization?.replace("Bearer ", "")
if (!token) throw new UnauthorizedException()
try {
// payload: { sub: userId, tenantId, role }
req.user = await this.jwt.verifyAsync(token)
return true
} catch {
throw new UnauthorizedException()
}
}
}If you would rather not build identity yourself, a managed provider (Auth0, Clerk, Cognito or similar) is a reasonable choice. Keep the guard layer anyway so the API stays the authority on permissions.
Which database should a SaaS use?
PostgreSQL is the default I would reach for. It is relational, which suits business data with clear relationships, it supports transactions, JSONB for flexible fields, full-text search, and row-level security, which matters a great deal for multi-tenancy.
Add other stores only for specific jobs: Redis for caching, rate limiting and queues; object storage for uploads; a search engine or analytics database when Postgres stops being a good fit for that workload.
How should multi-tenancy be implemented?
Multi-tenancy means many customers share your application while their data stays separate. There are three common models.
| Model | Isolation | Operational cost | Best for |
|---|---|---|---|
Shared database, shared schema (tenant_id column) | Logical, enforced by queries and row-level security | Lowest: one schema to migrate and monitor | Most B2B SaaS products and MVPs |
| Schema per tenant | Stronger; separate tables per customer | Medium: migrations must run per schema | Moderate tenant counts with stricter isolation needs |
| Database per tenant | Strongest; separate databases | Highest: many databases to run, migrate and back up | Regulated industries and large enterprise contracts |
Enforce isolation in the database, not only in code
With a shared schema, every table has a tenant_id. The risk is a developer forgetting a WHERE tenant_id = ... clause. PostgreSQL row-level security (RLS) protects against that by applying the filter automatically.
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE projects FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON projects
USING (tenant_id = current_setting('app.tenant_id')::uuid);Then set the tenant for the duration of each transaction, using the id from the verified token:
await db.transaction(async (tx) => {
// true = setting is local to this transaction
await tx.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId])
return tx.query("SELECT id, name FROM projects ORDER BY created_at DESC")
})How should a SaaS handle background jobs?
Anything slow, flaky or not needed for the immediate response belongs in a queue: sending emails, generating reports, processing uploads, calling third-party APIs, running AI tasks and delivering webhooks. In the Node.js ecosystem, BullMQ on top of Redis is a common and well-supported choice.
import { Queue, Worker } from "bullmq"
const connection = { host: process.env.REDIS_HOST, port: 6379 }
// Producer: called from a NestJS service
export const reports = new Queue("reports", { connection })
await reports.add(
"generate",
{ tenantId, reportId },
{ attempts: 5, backoff: { type: "exponential", delay: 2000 }, removeOnComplete: true },
)
// Consumer: runs in a separate worker process
new Worker(
"reports",
async (job) => {
await generateReport(job.data.tenantId, job.data.reportId)
},
{ connection, concurrency: 5 },
)Make jobs idempotent, meaning running the same job twice has the same result as running it once. Retries are only safe if repeated execution cannot double-charge a customer or send a duplicate email.
How can a SaaS application's performance be optimized?
- Measure first. Add request tracing and slow-query logging before changing anything.
- Index for real queries. Add indexes that match your
WHEREandORDER BYpatterns, includingtenant_idas the leading column on tenant-scoped tables. - Cache deliberately. Cache expensive, read-heavy results in Redis with clear invalidation rules.
- Paginate everything. Never return unbounded lists from the API.
- Keep the frontend light. Prefer Server Components and stream slow sections with Suspense.
How should a SaaS application scale?
Scale in stages and let metrics tell you when to move to the next one.
- Run multiple stateless copies of the Next.js app and the NestJS API behind a load balancer.
- Add a read replica or connection pooling (such as PgBouncer) when the database becomes the bottleneck.
- Scale workers independently of the API based on queue depth.
- Extract a separate service only when a module has a clear boundary and a distinct scaling or ownership need.
Is Next.js with NestJS the right choice?
Trade-offs of this stack
Pros
- TypeScript across the stack, with a clear separation of UI and business logic.
- NestJS modules give a natural path from modular monolith to services.
- Next.js covers SEO-friendly public pages and the authenticated app.
- Large ecosystems and hiring pool for both frameworks.
Cons
- Two deployables to build, host and monitor instead of one.
- Shared types need a shared package or generated API client.
- NestJS has a learning curve (decorators, dependency injection).
- For a very small MVP, a single full-stack Next.js app can be faster to ship.
Common SaaS architecture mistakes to avoid
- Splitting into microservices too early. It multiplies deployment, debugging and data-consistency problems before there is a scaling need.
- Trusting tenant ids from the client. Always derive them from verified credentials.
- Relying on application code alone for isolation. Add row-level security as a safety net.
- Doing slow work inside requests. It hurts latency and makes failures user-visible.
- Skipping observability. Without logs, metrics and alerts, you cannot find problems or prove improvements.
- Over-engineering before validation. Prove the product first; see how I approach shipping an MVP in six weeks.
Conclusion
Next.js and NestJS are a strong pairing for SaaS because they separate concerns cleanly: Next.js for a fast, SEO-friendly interface, NestJS for rules, security and data. Start as a modular monolith on PostgreSQL, enforce tenant isolation in the database, move slow work into queues, and add complexity only when measurements demand it.
If you are planning a SaaS product and want an experienced engineer to review your architecture or build the first version, get in touch. You can also see the products I have worked on and my skills and expertise.
FAQs
Follow-up questions about billing, shared types and when this stack is more than you need.
Yes. Next.js can serve SEO-friendly public pages and an authenticated application from one codebase. Server Components reduce client-side JavaScript, and its routing, layouts and data fetching suit dashboards and marketing pages alike.
Express is minimal and leaves structure to you. NestJS adds modules, dependency injection, guards and validation pipes out of the box, which keeps larger backends consistent and testable. For a small API, Express is fine; for a growing SaaS backend, NestJS's structure usually pays off.
For most B2B SaaS products and MVPs, a shared database and schema with a tenant_id column, protected by PostgreSQL row-level security, is the best starting point. Choose schema-per-tenant or database-per-tenant only when contracts or regulations demand stronger isolation.
Use a queue such as BullMQ backed by Redis. The API enqueues jobs, and separate worker processes consume them with retries and backoff. Make jobs idempotent so a retry cannot cause duplicate side effects.
Usually not at the start. A well-structured modular monolith with stateless, horizontally scalable instances, a managed database and queue-backed workers can carry a product a long way. Extract services only when there is a clear boundary and a measured reason.
Use a payment provider such as Stripe rather than building billing yourself. Create customers and subscriptions through the provider, listen to its webhooks to update your own subscription state, process webhooks idempotently, and check entitlements on the server so the UI never decides what a customer may access. Stripe's webhook documentation covers signature verification and retries.
Two reliable options: keep both apps in one monorepo (for example with pnpm workspaces, Nx or Turborepo) and share a package of types or validation schemas, or generate an OpenAPI spec from NestJS with @nestjs/swagger and produce a typed client for Next.js from it. The OpenAPI route also works for a future mobile app.
For a small MVP that is mostly CRUD, has one web client and little background processing, Next.js Route Handlers and Server Actions can be enough and are faster to ship. Add NestJS when several clients (web, mobile, partners) need the same API, when domain logic grows complex, or when you need dedicated workers and many integrations.
References
- Server and Client Components — Next.js documentation
- NestJS documentation: Guards — NestJS documentation
- PostgreSQL: Row Security Policies — PostgreSQL documentation
- BullMQ documentation — BullMQ
- The Twelve-Factor App — 12factor.net
- #SaaS
- #Next.js
- #NestJS
- #Architecture
- #Multi-tenancy
Keep reading

Next.js & React
Next.js App Router: Patterns I Reach for on Every Project
Server Components, route groups, streaming and server actions — the handful of patterns that keep my Next.js codebases fast and easy to reason about.
- Published
- Updated
- 8 min read

Cloud & DevOps
Scaling a Node.js API on GCP Without Over-Engineering
From a single Cloud Run service to a resilient, observable backend — what to add at each stage of growth, and what to skip until you need it.
- Published
- Updated
- 8 min read

SaaS & MVP
How I Ship a Production-Ready MVP in Six Weeks
A practical playbook for founders: what to cut, what to keep, and how to sequence the work so you launch fast without building a house of cards.
- Published
- Updated
- 7 min read