Give Google Antigravity, Claude Code, Cursor, OpenAI Codex, or Windsurf a locked, security-first architecture for Next.js 16 + React 19 + Supabase β so your agent stops improvising tenant isolation and starts enforcing it.
π Quick Start β’ π― Why TidyFactor/Next β’ π Tenant Isolation β’ β‘ 15-Stage Lifecycle β’ π Perf Engine β’ β FAQ β’ π Ψ¨Ψ§ΩΨΉΨ±Ψ¨ΩΨ©
- π― Why TidyFactor/Next
- π Quick Start
- π Architectural Value Proposition
- π Locked Tenant Isolation Model
- β‘ 15-Stage SaaS Command Lifecycle
- π Performance & Optimization Engine
- π‘οΈ RLS Policy Matrix & Auth Hooks
- π Project Memory & ARCHITECTURE.md
- β FAQ
- ποΈ The TidyFactor Ecosystem
- ποΈ TidyFactor Skill Methodology & Governance
- π€ Contributing
- π¨βπ» Support
- π License
Most Next.js agent skills teach your AI how to write idiomatic code β App Router conventions, caching APIs, and bundle-size tweaks. That is necessary, but it does not stop an agent from shipping a query that accidentally leaks Tenant A's data into Tenant B's dashboard.
TidyFactor/Next sits one layer deeper: it is an architecture and hard security contract, not just a style guide.
| Dimension | Generic Next.js Skills | tidyfactor-next |
|---|---|---|
| What it teaches | Idiomatic App Router, React 19 RSC boundaries, caching | Multi-tenant architecture + non-negotiable Postgres RLS boundary |
| Scope | Breadth: Many small, composable coding snippets | Depth: One vertical (multi-tenant SaaS), owned end-to-end |
| Failure mode prevented | Slow client components, suboptimal bundles | Cross-tenant data leaks, forgotten WHERE tenant_id = ... clauses |
| Performance scope | Basic production advice | Dual engine: 8 runtime optimization tiers + 6 dev-environment bottleneck models |
| Governance score | Unverified | 100% Architect Score (passes all TidyFactor Skill Architect rules) |
| Use together? | β | β β Install both; they complement each other perfectly |
Tip
If you are building a SaaS where a cross-tenant data leak means a lawsuit, tidyfactor-next is the foundational guardrail layer your AI agent needs in addition to general React best practices.
# Interactive project wizard β scaffolds a new multi-tenant SaaS project
npx @tidyfactor/cli-next
# Or inject the skill directly into an existing Next.js repository
npx @tidyfactor/cli-next add-skill| AI Agent | Workspace Skill Path |
|---|---|
| Google Antigravity | .agents/skills/tidyfactor-next/ or global ~/.gemini/config/skills/ |
| Claude Code | .claude-skill/skills/tidyfactor-next/ |
| Cursor / Codex / Windsurf | .agents/skills/tidyfactor-next/ |
Once installed, invoke /init or /brief inside your AI agent to discover project baselines and scaffold your ARCHITECTURE.md single source of truth!
graph TD
UserReq["π Incoming Request"] --> Edge["π‘οΈ Edge Middleware<br/>(Fail-Closed Tenant Resolution)"]
Edge --> Context["π¦ Tenant Context<br/>(tenant_id + JWT Claims)"]
Context --> App["β‘ Next.js 16 App Router<br/>(Server Components & Actions)"]
App --> Query["π Pluggable Query Layer<br/>(Supabase JS / Drizzle / Prisma)"]
Query --> Postgres["π PostgreSQL Database"]
Postgres --> RLS["π Row Level Security (RLS)<br/>USING (tenant_id = auth.jwt() ->> 'tenant_id')"]
RLS --> Data["β
Isolated Tenant Data"]
| For Fullstack Engineers | For SaaS Founders & CTOs | For AI Coding Agents |
|---|---|---|
Locked Tenant Isolation: Shared schema with tenant_id + Postgres RLS. No schema-per-tenant migration hell or multi-DB connection pooling chaos. |
Zero Data-Leak Guarantee: Hard security boundary at the database layer; application bugs cannot expose Tenant A's records to Tenant B. | Context-Efficient Dispatcher: Lightweight SKILL.md router loads only ~350 tokens at start, pulling memory only on demand. |
Pluggable Query Layer: Choose Supabase JS, Drizzle ORM, or Prisma once during init. All downstream code adheres strictly to your choice. |
Custom JWT Access Token Hook: Injects verified tenant_id and role server-side at token issuanceβnever trusted from client input. |
Deterministic Workflows: Every command runs against a strict, quantifiable validation checklist before shipping. |
| Fail-Closed Resolution: Edge middleware resolves tenant via subdomain, custom domain, or session claim, failing closed (404/403) on error. | Zero Lock-in Architecture: Pure Next.js App Router and PostgreSQL standards with zero black-box vendor runtime dependencies. | 100% Governance Compliance: Fully compliant (8/8) with the official TidyFactor Skill Architect governance specification. |
| Evidence-Based Perf Engine: Diagnoses RAM, CPU, and Disk bottlenecks before touching code; benchmark-backed DELTA verification. | Predictable Infrastructure Cost: Identifies bloated client bundles and server secret leaks before deployment. | SaaS Safety Boundary: Automatically prohibits performance optimizations that weaken RLS or tenant isolation. |
tidyfactor-next enforces strict, non-negotiable isolation rules across the entire lifecycle:
-- Standard Tenant Isolation Policy (Pattern 1)
ALTER TABLE public.organizations ENABLE ROW LEVEL SECURITY;
CREATE POLICY "organizations_tenant_isolation_select" ON public.organizations
FOR SELECT USING (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid);
CREATE POLICY "organizations_tenant_isolation_insert" ON public.organizations
FOR INSERT WITH CHECK (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid);
CREATE POLICY "organizations_tenant_isolation_update" ON public.organizations
FOR UPDATE USING (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid)
WITH CHECK (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid);
CREATE POLICY "organizations_tenant_isolation_delete" ON public.organizations
FOR DELETE USING (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid);- RLS is the Security Boundary: Application-layer
WHERE tenant_id = ...is only a query-plan hint. If RLS is disabled, the system is defective by definition. service_roleKey Isolation: Never exposed to client bundles or public endpoints. Used exclusively in server-only contexts with re-verified tenant context.- Edge Context Propagation: Tenant identity is resolved once at the edge and passed downβnever re-derived haphazardly in deep component trees.
- Cross-Tenant Operations Review: Admin impersonation, cross-tenant migrations, or platform analytics must be isolated and flagged as security review triggers.
The entire SaaS engineering lifecycle is structured into 15 deterministic commands with 100% operational coverage:
| Stage | Command | User Intent | What It Loads | Status |
|---|---|---|---|---|
| 0. Discovery | brief |
Pre-flight CDL discovery & baseline architecture cache | references/workflows/brief.md + decision-points.md + quality-bar.md |
β Built |
| 1. Foundation | init |
Scaffold new multi-tenant project & generate ARCHITECTURE.md |
references/workflows/init.md + spec.md + architecture-doc-skeleton.md |
β Built |
| 1. Foundation | tenant |
Tenant resolution, context propagation, lifecycle | references/workflows/tenant.md + references/memory/spec.md |
β Built |
| 2. Security | rls |
RLS policy authoring, 4-policy pattern, leak audit | references/workflows/rls.md + spec.md + rls-patterns.md |
β Built |
| 2. Security | auth |
Supabase Auth, custom JWT claims hook, RBAC/ABAC | references/workflows/auth.md + spec.md + auth-patterns.md |
β Built |
| 3. Data | data |
Schema, migrations, transactions, constraints | references/workflows/data.md + references/memory/decision-points.md |
β Built |
| 3. Data | storage |
Tenant-scoped buckets, signed URLs, storage RLS | references/workflows/storage.md + references/memory/cache-storage-rules.md |
β Built |
| 4. Application | api |
Route handlers, server actions, API contracts | references/workflows/api.md + client-server-boundaries.md + react-perf-rules.md |
β Built |
| 4. Application | app |
App Router, React 19, RSC boundaries, Suspense | references/workflows/app.md + client-server-boundaries.md + react-perf-rules.md |
β Built |
| 5. Quality | test |
Unit, integration, RLS coverage, E2E security tests | references/workflows/test.md + references/memory/quality-bar.md |
β Built |
| 5. Quality | observe |
Tracing, tenant-scoped audit logs, health checks | references/workflows/observe.md + references/memory/quality-bar.md |
β Built |
| 6. DevOps | deploy |
CI/CD, environments, rollback, point-in-time backups | references/workflows/deploy.md + references/memory/spec.md |
β Built |
| 6. DevOps / Perf | perf |
Dev & runtime performance audit, bottleneck diagnosis, safe perf | references/workflows/audit-dev-perf.md + perf-optimization-rules.md + react-perf-rules.md |
β Built |
| 7. Operations | incident |
Disaster recovery, tenant leak remediation runbooks | references/workflows/incident.md + references/memory/spec.md |
β Built |
| 7. Operations | audit |
Full-stack multi-tenant architecture compliance audit | references/workflows/audit.md + references/memory/quality-bar.md |
β Built |
tidyfactor-next encapsulates 40+ runtime optimization rules categorized into 8 impact-ranked tiers (references/memory/react-perf-rules.md):
-
Tier 1: Eliminating Waterfalls (
async-*) [CRITICAL]: Check synchronous conditions beforeawait, deferawaitto consuming branches, parallelize independent queries withPromise.all(), stream async subtrees with<Suspense>. -
Tier 2: Bundle Size Optimization (
bundle-*) [CRITICAL]: Avoid barrel files, configureoptimizePackageImports, lazy-load heavy widgets withnext/dynamic({ ssr: false }), defer 3rd-party scripts. -
Tier 3: Server-Side Performance (
server-*) [HIGH]: Wrap per-request data fetchers withReact.cache(), offload non-blocking telemetry and audit logs to Next.js 16after(), pass only minimal serialized DTOs across the RSC$\to$ RCC boundary. -
Tier 4: Client-Side Data Fetching (
client-*) [MEDIUM-HIGH]: SWR / TanStack Query automatic deduplication, passive scroll listeners. -
Tier 5: Re-render Optimization (
rerender-*) [MEDIUM]: Pure derived state in render (never synchronize viauseEffect), avoiduseMemoon cheap primitives, lazyuseStateinitializers,startTransition/useDeferredValue. -
Tier 6: Rendering Performance (
rendering-*) [MEDIUM]: CSScontent-visibility: auto, hoist static JSX elements outside render, use explicit conditionals. -
Tier 7: JavaScript Performance (
js-*) [LOW-MEDIUM]: Layout thrashing prevention (batch DOM read/write),Set/Map$O(1)$ lookups,toSorted()immutability. -
Tier 8: Advanced React Patterns (
advanced-*) [LOW]: Extract non-reactive callback logic withuseEffectEvent, single-mount app initialization.
Tackles dev-server startup slowness, sluggish HMR, RAM bloat, and disk I/O through 6 Causality Models:
- Model A (RAM Pressure β Disk I/O): Memory saturation causing OS paging to swap.
- Model B (Large Dependency Graph β CPU/RAM): Massive module trees slowing cold starts.
- Model C (Slow Storage β Cache I/O):
.next/cacheI/O bottlenecks. - Model D (TypeScript Scope Overreach): Wide
includescopes analyzing generated or test files. - Model E (ESLint / Tooling Overhead):
typeCheckedrules running without caching. - Model F (Watch Boundary Overflow): Thousands of media uploads monitored by file watchers.
graph TD
Finding["π Optimization Finding"] --> Tier{"Safety Classification"}
Tier -->|π’ Green| GreenAction["β
Apply Automatically<br/>(Unused deps, tsconfig scope, watchIgnore)"]
Tier -->|π‘ Yellow| YellowPipeline["π 8-Step Evidence Pipeline<br/>(optimizePackageImports, barrel restructure)"]
Tier -->|π΄ Red| RedForbidden["π« Permanently Forbidden<br/>(DB schema, RLS, Auth, Tenant Isolation)"]
- π’ Green (Safe): Unused dependency cleanup,
dependenciesvsdevDependenciescorrection,tsconfig.jsonscope tightening,.gitignore&watchIgnorefixes. - π‘ Yellow (Review Required): Evidence-based
optimizePackageImports, barrel import restructuring, client-to-server component conversion. - π΄ Red (Permanently Forbidden): Modifying database schema, RLS policies, auth flows, tenant isolation models, or globally disabling caching.
CREATE TABLE public.tenant_memberships (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
role text NOT NULL DEFAULT 'member',
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (tenant_id, user_id)
);
ALTER TABLE public.tenant_memberships ENABLE ROW LEVEL SECURITY;
CREATE POLICY "memberships_self_select" ON public.tenant_memberships
FOR SELECT USING (user_id = auth.uid());CREATE OR REPLACE FUNCTION public.custom_access_token_hook(event jsonb)
RETURNS jsonb LANGUAGE plpgsql STABLE AS $$
DECLARE
claims jsonb;
membership record;
BEGIN
claims := event->'claims';
SELECT tenant_id, role INTO membership
FROM public.tenant_memberships
WHERE user_id = (event->>'user_id')::uuid
LIMIT 1;
IF membership IS NOT NULL THEN
claims := jsonb_set(claims, '{tenant_id}', to_jsonb(membership.tenant_id));
claims := jsonb_set(claims, '{role}', to_jsonb(membership.role));
END IF;
RETURN event;
END;
$$;During /init, the skill generates an ARCHITECTURE.md file in your project root. This document serves as the Single Source of Truth for architectural decisions across AI agent sessions:
- Locked Platform Choices: App Router, React 19, TypeScript strict, Postgres RLS.
- Chosen Once Decisions: Query layer (Supabase JS, Drizzle, Prisma), tenant resolution strategy, auth provider, role model.
- Performance Context: Known bottlenecks, storage strategy, active baseline, last audit timestamp & git commit SHA.
- ADR Log: Append-only register recording significant architectural decisions.
- Open Risks & Tech Debt: Prioritized register (P0βP3) tracked across
perf,rls,audit, andincidentcommands.
Does this replace generic Next.js skills like react-best-practices?
No β use both.
tidyfactor-next governs multi-tenant architecture, data isolation, and Postgres RLS security contracts. General best-practice skills focus on general React idioms and client-side styling. They do not overlap; tidyfactor-next incorporates runtime optimization rules directly.
Which AI coding agents are supported?
Google Antigravity, Claude Code, Cursor, OpenAI Codex, and Windsurf are all supported with 100% behavioral parity.
Can I use Drizzle ORM or Prisma instead of the Supabase JS client?
Yes. The query layer is a "chosen-once" decision made during
init or brief. All generated schema models, queries, and repositories follow your confirmed choice.
What happens if RLS is accidentally disabled on a table?
By this skill's definition, the system is defective. The
/rls and /audit commands include automated leak-audit queries against pg_tables and pg_policies to flag unshielded tables immediately.
How does the Contextual Decision Layer (CDL) work?
The CDL runs a single-round pre-flight interview via
/brief and caches baseline stack choices in .tidyfactor/next-brief.md, allowing downstream commands to execute silently without repeating questions.
TidyFactor is a modular web architecture and AI coding agent skill ecosystem built on clear separation of concerns across the product lifecycle:
TidyFactor Organization (github.com/TidyFactor)
β
βββ Design Skills
β βββ Cinematic β Experience / "Wow" (Apple Γ Cartier Scroll-Driven Landing Pages)
β βββ Design β Prototype / "Build" (Code-Native UI Design Engine & Figma Alternative)
β βββ Styler β Production / "Ship" (Framework Styler & RTL Polish Engine)
β
βββ Development Skills
β βββ HTML β Content & Static (Semantic SEO & Static Platform Starter)
β βββ HTMX β Hypermedia (Server-Driven Micro-Interactions)
β βββ JS β Vanilla SPA (Framework-Free Reactive ES Modules)
β βββ PHP β Server-Rendered (Modern PHP 8.x Component UI & Architecture)
β βββ Next β Multi-Tenant SaaS (Next.js 16, React 19, Supabase RLS & Dev-Perf)
β
βββ Growth Skills
βββ Marketing β Growth / Revenue (Direct Response, Pillar SEO & Content Lifecycles)
| Track | Category | GitHub Repository | Agent Skill | NPM Package |
|---|---|---|---|---|
| Next | Development | TidyFactor/Next |
tidyfactor-next |
@tidyfactor/next |
| Cinematic | Design | TidyFactor/Cinematic |
tidyfactor-cinematic |
@tidyfactor/cinematic |
| Design | Design | TidyFactor/Design |
tidyfactor-design |
@tidyfactor/design |
| Styler | Design | TidyFactor/Styler |
tidyfactor-styler |
@tidyfactor/styler |
| HTML | Development | TidyFactor/HTML |
tidyfactor-html |
@tidyfactor/html |
| HTMX | Development | TidyFactor/HTMX |
tidyfactor-htmx |
@tidyfactor/htmx |
| JS | Development | TidyFactor/JS |
tidyfactor-js |
@tidyfactor/js |
| PHP | Development | TidyFactor/PHP |
tidyfactor-php |
@tidyfactor/php |
| Marketing | Growth | TidyFactor/Marketing |
tidyfactor-marketing |
@tidyfactor/marketing |
tidyfactor-next passes all 8 Architectural Governance Rules under tidyfactor-skill-architect:
- β
Dispatcher Discipline:
SKILL.mdroutes commands without executing tasks (~350 tokens). - β One Workflow = One Outcome: Every workflow has a single deliverable with an explicit validation checklist.
- β Operational Memory: Pure SQL templates, schemas, and architecture rulesβzero narrative prose.
- β No Empty Structures: Clean, flattened architecture without single-file folders.
- β Philosophy Isolation: Technical execution separated from marketing commentary.
- β Trigger-Justified Growth: Commands added per verifiable SaaS lifecycle stages.
- β
Security & Quality Bar: Automated RLS coverage queries (
pg_tables,pg_policies) and leak diagnosis. - β Cross-Platform Parity: 100% identical behavior across Antigravity, Claude Code, Cursor, and Codex.
We welcome community contributions, custom query layer adapters, and workflow refinements!
Please read our CONTRIBUTING.md and CODE_OF_CONDUCT.md before opening a Pull Request. All proposed workflows and memory extensions must satisfy the tidyfactor-skill-architect governance rules.
- π Website: tidyfactor.com
- π Documentation: tidyfactor.com/documentation
- π€ Commercial Partner: Alwkala Digital Agency
- π GitHub Organization: github.com/TidyFactor
- π§ Inquiries: hello@tidyfactor.com
- π Official Website: https://tidyfactor.com/
- π Official Documentation: https://tidyfactor.com/documentation
- π€ Official Partner Website: Alwkala Digital Agency
- π GitHub Organization: github.com/TidyFactor
- π§ Business Inquiries: hello@tidyfactor.com
- π± WhatsApp: +20 101 665 6899
- π Phone: +20 101 665 6899
- π Location: Cairo, Egypt
Licensed under the Apache License 2.0. Copyright (c) 2026 TidyFactor & Alwkala.

