SaaS & MVP Development

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.

Habib Ur RehmanBy Senior Full Stack Engineer & MVP Partner
  • Published
  • 11 min read
Architecture diagram of a SaaS application: Next.js frontend, NestJS API, PostgreSQL database, Redis queue and background workers

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.

Architecture diagram: browser to Next.js frontend, then NestJS API, which connects to PostgreSQL, a Redis queue with background workers, and object storage
Reference architecture for a Next.js and NestJS SaaS application.

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.

TSXapp/(app)/projects/page.tsx
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?

Comparison of API styles for a Next.js and NestJS SaaS
ApproachBest forTrade-offsFit with NestJS
REST + OpenAPISimple CRUD, public APIs, mobile and third-party clientsPossible over- or under-fetching; versioning needs disciplineExcellent: controllers and @nestjs/swagger
GraphQLMany clients with very different data needsMore complexity: caching, N+1 queries, query cost limitsGood: code-first and schema-first modes
tRPCOne TypeScript monorepo with a web-only clientCouples client and server; weaker for public or mobile APIsPossible 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.

TypeScriptauth/jwt-auth.guard.ts
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.

Comparison of three multi-tenancy models: shared schema with tenant_id, schema per tenant, and database per tenant
Three ways to isolate tenant data in PostgreSQL.
Multi-tenancy models compared
ModelIsolationOperational costBest for
Shared database, shared schema (tenant_id column)Logical, enforced by queries and row-level securityLowest: one schema to migrate and monitorMost B2B SaaS products and MVPs
Schema per tenantStronger; separate tables per customerMedium: migrations must run per schemaModerate tenant counts with stricter isolation needs
Database per tenantStrongest; separate databasesHighest: many databases to run, migrate and back upRegulated 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.

SQLmigrations/enable-rls.sql
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:

TypeScriptdatabase/tenant-scope.ts
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.

Background job flow: request arrives, API validates and enqueues a job, worker processes it with retries, result is stored and the client is notified
A request that triggers slow work returns immediately; a worker finishes the job.
TypeScriptjobs/reports.ts
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?

  1. Measure first. Add request tracing and slow-query logging before changing anything.
  2. Index for real queries. Add indexes that match your WHERE and ORDER BY patterns, including tenant_id as the leading column on tenant-scoped tables.
  3. Cache deliberately. Cache expensive, read-heavy results in Redis with clear invalidation rules.
  4. Paginate everything. Never return unbounded lists from the API.
  5. 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.

  1. Run multiple stateless copies of the Next.js app and the NestJS API behind a load balancer.
  2. Add a read replica or connection pooling (such as PgBouncer) when the database becomes the bottleneck.
  3. Scale workers independently of the API based on queue depth.
  4. 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.

References

  1. Server and Client Components — Next.js documentation
  2. NestJS documentation: Guards — NestJS documentation
  3. PostgreSQL: Row Security Policies — PostgreSQL documentation
  4. BullMQ documentation — BullMQ
  5. The Twelve-Factor App — 12factor.net
  • #SaaS
  • #Next.js
  • #NestJS
  • #Architecture
  • #Multi-tenancy
  • A code editor with dark theme showing JavaScript test code on a monitor

    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
    Read article
  • A large data centre hall with server cabinets and blue network cables overhead

    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
    Read article
  • A product team placing colourful sticky notes on a glass wall while planning an MVP

    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
    Read article