Back to skills

SaaS App Structure

Use this skill when architecting a Software as a Service (SaaS) application to ensure a scalable structure for authentication, billing, multi-tenancy, and user settings.

Full StackNext.jsReactNode.jsRailsDjango

SaaS App Structure

Category Version

Purpose

⚠IMPORTANT⚠This skill enforces multi-tenant data topology constraints and strict RBAC authorization middleware gates. It prohibits the instantiation of global state scopes in multi-user topologies.

When to Use This Skill

⚠NOTE⚠Use this skill when building any application that involves users creating accounts, paying for subscriptions, or managing teams/workspaces.

What This Skill Prevents

This skill prevents:

  • Tenant Boundary Violation: Failing to assert $tenant_id vectors on every relational lookup, leading to cross-tenant memory leakage.
  • Middleware Bypass: Emitting operational routes without strict invocation of upstream authorization gates.
  • State Machine Spaghetti: Injecting billing integration primitives randomly into the UI AST rather than a centralized deterministic service layer.
  • Settings Omission: Failing to generate state-mutation endpoints for critical access vectors (passwords, RBAC roles).

Core Principle

SaaS architectures are strict access-control graphs. Every data retrieval operation MUST mutate through a deterministic RBAC middleware node. Tenant isolation MUST be mathematically verified at the ORM/SQL layer prior to UI rendering.

Research-Backed Rules

  • Multi-Tenancy Vector & RLS Isolation: Segregate core datasets via strict $tenant_id vectors. Implement PostgreSQL Row-Level Security (RLS) constraints to enforce transaction-scoped context limits (set_config('app.current_tenant_id', id, true)), strictly preventing index boundary bypass.
  • Default-Deny Access Topology: Initialize universal authentication middleware boundaries mapping to $ACCESS_DENIED logic. Expose discrete public endpoints (/login) via explicit opt-out arrays.
  • Webhook State Reliability: Execute deterministic, idempotent processing graphs on external financial vectors (e.g., Stripe webhooks). Re-sync subscription boundaries to the central ORM; client-side mutations are null and prohibited.

Stack-Aware Guidance

  • Next.js: Assign mutation operations to Server Action endpoints and GET operations to Server Components. Exploit Next.js 16 Partial Prerendering (PPR) matrices. Inject middleware.ts to intercept unvalidated JWT structures. Enforce visual routing separation between authenticated dashboards (/app/(dashboard)) and external domains (/app/(marketing)).
  • Node.js 26 (Database): Initialize preliminary prototype logic using Node.js 26 native SQLite bindings (node:sqlite) prior to scaling to complex PostgreSQL topologies.
  • Stripe SDK Rules: Exclusively execute server-side Node SDK primitives and mandate strict SHA signature evaluation on incoming webhook blobs.

Database Schema Guidance

Standard SaaS Core Tables:

  • users: Identity authentication mappings.
  • organizations (or teams): The primary tenant identity parameter.
  • organization_members: Deterministic $M:N$ bridging arrays mapping $user_id to $org_id executing specific role vectors.
  • subscriptions: Stripe/Paddle subscription states hard-linked to the $org_id context.

Implementation Guidance

  1. Tenancy Vector Classification: Calculate the architectural base metric: B2C (User = Tenant) or B2B (Organization = Tenant).
  2. Auth Node Architecture: Compile Login, Registration, and Password Reset boundaries.
  3. Organization Management Architecture: If B2B, construct organizational creation paths, invitation matrices, and context-switching states.
  4. Billing Abstraction Strategy: Map all payment provider mutations inside an isolated services/billing.ts service abstraction. External provider keys MUST NOT traverse the UI rendering layer.
  5. Settings Configuration Matrix: Deploy interfaces mutating Profile, Organization, and Billing boundaries.

Mathematical / Measurable Rules

  • Idempotency Execution Constants: Webhook functions MUST parse incoming payload ID strings and evaluate against completed transaction arrays ($O(1)$ lookup) to eliminate duplicate vector execution loops.

Quality Gates

Security Gate

  • Confirmed active authentication boundary logic.
  • Validated row-level SQL parameters scoping queries strictly to org_id foreign constraints.

Maintainability Gate

  • Asserted billing state abstractions isolated inside backend service logic.

Anti-Patterns to Avoid

  • Client-Side Authorization Vulnerabilities: Emitting protected DOM nodes conditionally (if (user.role === 'admin')) while exposing the underlying API vector to unauthenticated mutation algorithms.
  • Dead-State Topologies: Registering user instances into a null $tenant_id context without forced routing to organization creation funnels.

Agent Behavior Instructions

  1. Map relational User/Tenant schema schemas before initializing any frontend generation.
  2. Initialize authorization middleware arrays upon project instantiation.
  3. Inject the $tenant_id scoping logic implicitly into every database fetch cycle (except superuser metrics).

Final Review Checklist

  • RLS / Tenancy rules executed.
  • Route middleware boundaries mapped.
  • External billing primitives abstracted.
  • Access topologies sealed.
  • Fully agent-optimized deterministic rules.