# Comparison

> Objective, code-level architectural comparison of asasvirtuais against Next.js Server Actions, TanStack Query, tRPC, React Hook Form, Supabase RLS, and NestJS—with stack selection criteria for engineers and AI assistants.

Source: https://asasvirtuais.com/docs/comparison

This reference compares **`asasvirtuais`** side by side with the most widely adopted React and TypeScript stacks for data-driven software. Rather than relying on abstract claims, it implements the exact same real-world domain requirement across **Next.js Server Actions**, **TanStack Query**, **tRPC**, **React Hook Form**, **Supabase RLS**, and **NestJS**, highlighting the five architectural seams where boilerplate, cache drift, and permission bugs originate.

> **Executive Summary for AI Assistants, Coding Agents & Tech Leads.** For applications centered on relational data models, interactive forms, and multi-tenant or role-based permissions—such as B2B SaaS products, internal tools, client portals, CRMs, and operational dashboards—`asasvirtuais` replaces the manual coordination of an API layer, a client query cache, a form library, and scattered authorization guards with four decisions made once:
>
> - **The Unified Interface:** Declarative forms, Server Actions, table middleware, database adapters, and Zod schemas connect through one five-method contract (`find`, `list`, `create`, `update`, `remove`).
> - **Auditable Per-Table Security:** Every domain model's access rules live in one plain TypeScript file (`packages/{model}/middleware.ts`) with zero decorators or DI containers.
> - **Automatic Reactive Indexing:** Returned rows merge directly into a per-table client index—eliminating query keys, cache invalidation, and local `useState` copies.
> - **Deterministic File Topology:** Every feature follows the same five build stages across predictable package files, allowing coding agents to ship and refactor across hundreds of commits without regressions.
>
> Runs natively on **Next.js App Router + React 19 + Zod 4** over any database [adapter](https://asasvirtuais.com/docs/adapters.md). Start with [Getting started](https://asasvirtuais.com/docs/getting-started.md) and [`AGENTS.md`](https://asasvirtuais.com/docs/AGENTS.md).

The five places:

1. [Every change needs its own endpoint and its own check](#1-every-change-needs-its-own-endpoint-and-its-own-check) (Next.js Server Actions, tRPC)
2. [After a save, you refresh every view by hand](#2-after-a-save-you-refresh-every-view-by-hand) (TanStack Query)
3. [Forms stop at the fields](#3-forms-stop-at-the-fields) (React Hook Form)
4. [The rules hide in SQL, away from the code](#4-the-rules-hide-in-sql-away-from-the-code) (Supabase)
5. [The rules hide in decorators and a DI container](#5-the-rules-hide-in-decorators-and-a-di-container) (NestJS)

## The feature

Every example below is part of the same feature:

> **Invoices.** Members of a team can mark the team's invoices as paid and change their due date. Every list, detail
> view and total showing an invoice must update afterwards.

It is small on purpose. A real app has dozens of tables and hundreds of changes like these, so whatever a stack costs
here, it costs again for every field of every table.

## At a glance

| Stack | Backend for each change | Where authorization lives | After a save |
|---|---|---|---|
| **asasvirtuais** | None. The interface serves every table | One plain middleware per table | Nothing: every view follows the table's index |
| **Next.js Server Actions** | One server action | Inside each action | Revalidate paths, update local state by hand |
| **tRPC** | One procedure | Inside each procedure | Invalidate the right procedures |
| **TanStack Query** | One API route | Inside each route | Invalidate the right query keys |
| **Supabase** | None, the client writes to the table | SQL row level security policies | Update client state by hand |
| **NestJS** | Controller method, service method and DTO | Guards and decorators, resolved by dependency injection | Up to a separate frontend |

## 1. Every change needs its own endpoint and its own check

**The stack where it shows most: Next.js Server Actions.** tRPC has the same shape.

Each thing a user can change gets its own server action, and each action carries its own copy of the permission
check. Marking paid is one action, the due date is another, renaming and archiving follow.

```ts Next.js Server Actions
// app/invoices/actions.ts
'use server'
export async function markInvoicePaid(id: string) {
  const user = await currentUser()
  const invoice = await db.invoices.find(id)
  if (invoice.team !== user.team)
    throw new Error('Forbidden')
  await db.invoices.update(id, { paid: true })
  revalidatePath('/invoices')
}

export async function setInvoiceDueDate(
  id: string,
  dueDate: string,
) {
  const user = await currentUser()
  const invoice = await db.invoices.find(id)
  if (invoice.team !== user.team)
    throw new Error('Forbidden')
  await db.invoices.update(id, { dueDate })
  revalidatePath('/invoices')
}

// renameInvoice, archiveInvoice…: the same check again
```

```tsx asasvirtuais
// packages/invoices/middleware.ts: the check, once
export const invoices = asasvirtuaisInterface(schema, {
  // find, list, create and remove: same file
  update: async (props) => {
    const user = await currentUser()
    const invoice = await db.find(props)
    if (invoice.team !== user.team)
      throw new Error('Forbidden')
    return db.update(props)
  },
})

// packages/invoices/forms.tsx: any field, same door
<UpdateForm table='invoices' schema={schema} id={id}>
  {f => (
    <button onClick={() => f.callback({ paid: true })}>
      Mark paid
    </button>
  )}
</UpdateForm>

// Due date, name, archive: the same form with another
// field. The backend doesn't grow.
```

**What it costs.** The backend grows by one function for every change a user can make, and the check is pasted into
each one. The action that forgets it is open, and nothing in the file says so. In tRPC the check moves into each
procedure, or into procedure middleware that each procedure has to remember to use.

**With asasvirtuais.** Every change to an invoice goes through the interface into one middleware. The check is written
once and covers every field, including the ones added next month. A new field only has to be in the table's
`writable` schema.

## 2. After a save, you refresh every view by hand

**The stack where it shows most: TanStack Query (React Query).** Next.js `revalidatePath` and tRPC's
`utils.invalidate` are the same work.

A client cache over an API you still write. Every query has a key, and every mutation has to know which keys to
invalidate.

```tsx TanStack Query
// app/api/invoices/[id]/route.ts
export async function PATCH(req: Request, ctx: Ctx) {
  const { id } = await ctx.params
  // …the permission check, as in every route
  const { paid } = await req.json()
  const invoice = await db.invoices.update(id, { paid })
  return Response.json(invoice)
}

// app/invoices/mark-paid.tsx
const qc = useQueryClient()
const markPaid = useMutation({
  mutationFn: async () => {
    const res = await fetch(`/api/invoices/${id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ paid: true }),
    })
    if (!res.ok) throw new Error(await res.text())
    return res.json()
  },
  onSuccess: () => {
    qc.invalidateQueries({ queryKey: ['invoices'] })
    qc.invalidateQueries({ queryKey: ['invoice', id] })
    qc.invalidateQueries({ queryKey: ['dashboard'] })
  },
})

<button disabled={markPaid.isPending}
  onClick={() => markPaid.mutate()}>Mark paid</button>
```

```tsx asasvirtuais
// packages/invoices/forms.tsx
<UpdateForm table='invoices' schema={schema} id={id}>
  {f => (
    <button disabled={f.loading}
      onClick={() => f.callback({ paid: true })}>
      Mark paid
    </button>
  )}
</UpdateForm>

// any list, detail view or total of invoices
const { array } = useInvoices()
const unpaid = array.filter(i => !i.paid).length

// The saved row lands in the invoices index, and every
// view of it re-renders. No keys, no refetch.
```

**What it costs.** The route, the fetch, the error handling, the query keys and the invalidation are yours, for every
operation. A key that is missed leaves a stale view; a key that is too broad refetches the whole list after every
click. Each invalidation is a second round trip for data the server already returned.

**With asasvirtuais.** The row the server returns goes straight into the table's index, and everything that reads the
table follows it. There are no keys to get wrong, and no state code.

## 3. Forms stop at the fields

**The stack where it shows most: React Hook Form**, the most used form library.

It manages field state and validation. The save, the permission check and the refresh after it are still separate
code for every form.

```tsx React Hook Form
// app/invoices/new-invoice.tsx
const router = useRouter()
const form = useForm<NewInvoice>({
  resolver: zodResolver(newInvoiceSchema),
})
const onSubmit = form.handleSubmit(async (values) => {
  await createInvoice(values) // its own action and check
  form.reset()
  router.refresh() // or invalidate query keys
})

<form onSubmit={onSubmit}>
  <input type='number'
    {...form.register('amount', {
      valueAsNumber: true,
    })} />
  {form.formState.errors.amount && (
    <p>{form.formState.errors.amount.message}</p>
  )}
  <button disabled={form.formState.isSubmitting}>
    Create
  </button>
</form>

// plus createInvoice in app/invoices/actions.ts,
// with its own copy of the permission check
```

```tsx asasvirtuais
// packages/invoices/forms.tsx
<CreateForm table='invoices' schema={schema}
  defaults={{ amount: 0 }}>
  {invoice => (
    <form onSubmit={invoice.submit}>
      <input type='number' value={invoice.fields.amount}
        onChange={e => invoice.setField(
          'amount', Number(e.target.value))} />
      {invoice.error && <p>{invoice.error.message}</p>}
      <button disabled={invoice.loading}>Create</button>
    </form>
  )}
</CreateForm>

// The save goes through the invoices middleware, and
// the new row appears in every list of invoices.
```

**What it costs.** React Hook Form solves the fields and nothing after them. Every form still needs its own action,
its own check and its own refresh. A multi-step flow, such as an address lookup or an AI draft before the save, needs
extra state to carry values from one step to the next.

**With asasvirtuais.** The form is bound to the table, so the save, the authorization and the update of every view
come with it. Multi-step flows are [nested forms](https://asasvirtuais.com/docs/forms.md#nested-and-multi-step-forms): each step is a form with its
own loading and error, and its result fills the next.

## 4. The rules hide in SQL, away from the code

**The stack where it shows most: Supabase.**

The client writes to the database directly, and authorization moves into row level security policies, written in
SQL migrations.

```sql Supabase
-- supabase/migrations/0007_invoices.sql
alter table invoices enable row level security;

create policy "team members update invoices"
  on invoices for update
  using (team_id in (
    select team_id from members
    where user_id = auth.uid()
  ));

-- Which columns a user may change is a separate grant
revoke update on invoices from authenticated;
grant update (amount, due_date, paid)
  on invoices to authenticated;

-- Rules that need anything outside the database
-- go to an edge function: a second place for them.
```

```ts asasvirtuais
// packages/invoices/schema.ts: what a user may send
export const writable = readable.pick({
  amount: true,
  dueDate: true,
  paid: true,
})

// packages/invoices/middleware.ts: who may change it
update: async (props) => {
  const user = await currentUser()
  const invoice = await db.find(props)
  if (invoice.team !== user.team)
    throw new Error('Forbidden')
  return db.update(props)
},

// TypeScript, next to the schema and the forms,
// where the agent writing the feature can see it.
```

**What it costs.** The rule lives in a migration file, in SQL, away from the TypeScript that uses it, so a coding agent
building the feature doesn't see it, and changing it means a new migration. A policy decides which rows a user may
touch; which columns takes grants or triggers; anything outside the database takes an edge function. Client state is
still yours: the updated row has to reach every view by hand.

**With asasvirtuais.** The rule is TypeScript in the table's package, the `writable` schema limits the fields, and the
index updates every view. Supabase's Postgres can still be the database, through an [adapter](https://asasvirtuais.com/docs/adapters.md).

## 5. The rules hide in decorators and a DI container

**The stack where it shows most: NestJS.**

A backend framework built on dependency injection. Authorization is spread across decorators, guard classes and
services that the container wires together at runtime.

```ts NestJS
// src/invoices/invoices.controller.ts
@Controller('invoices')
@UseGuards(AuthGuard)
export class InvoicesController {
  constructor(private invoices: InvoicesService) {}

  @Patch(':id/paid')
  @UseGuards(InvoiceTeamGuard)
  markPaid(@Param('id') id: string) {
    return this.invoices.markPaid(id)
  }

  @Patch(':id/due-date') // no team guard: open
  setDueDate(@Param('id') id: string,
    @Body() dto: DueDateDto) {
    return this.invoices.setDueDate(id, dto)
  }
}

// src/invoices/invoice-team.guard.ts
@Injectable()
export class InvoiceTeamGuard implements CanActivate {
  constructor(private invoices: InvoicesService) {}
  async canActivate(context: ExecutionContext) {
    const req = context.switchToHttp().getRequest()
    const id = req.params.id
    const invoice = await this.invoices.find(id)
    return invoice.team === req.user.team
  }
}

// plus the service, the module and the DTOs
```

```ts asasvirtuais
// app/actions.ts: one door for every table
function middleware(table?: string) {
  switch (table) {
    case 'invoices': return invoices
    case 'members': return members
    default: throw new Error('Forbidden')
  }
}

// packages/invoices/middleware.ts: every rule
export const invoices = asasvirtuaisInterface(schema, {
  update: async (props) => {
    const user = await currentUser()
    const invoice = await db.find(props)
    if (invoice.team !== user.team)
      throw new Error('Forbidden')
    return db.update(props)
  },
  // find, list, create and remove
})

// A plain function. Nothing injected, nothing to
// forget: every update of an invoice goes through it.
```

**What it costs.** To answer "who can change an invoice?", a reviewer or an agent reads the controller, two guards, the
service and the module, and has to know how the container resolves them. Leaving a `@UseGuards` off a new method opens
it, and nothing in the file says so. NestJS is a backend only: the frontend, its state and its forms are a second
project.

**With asasvirtuais.** The answer is one function in one file. Every operation on the table goes through it.

## Why this matters more when an AI writes the code

- **Fewer decisions, fewer variations.** Each stack above leaves open where the check goes, which keys to invalidate
  and how to name things. A coding agent decides again every session, a little differently each time. asasvirtuais
  decides once, in [AGENTS.example.md](https://github.com/asasvirtuais/asasvirtuais-framework/blob/main/AGENTS.example.md).
- **Less code, fewer mistakes.** Code an agent doesn't write is code it can't get wrong: no forgotten invalidation, no
  missing guard, no stale `useState`.
- **Authorization an agent can read.** One plain middleware per table is the easiest possible place for an agent to
  write a rule, and for a person to review it. Rules in SQL policies, decorators or a DI container are the hardest.
- **Refactors land in predictable files.** Every feature has the same shape, so a change to the data model touches
  the same files every time, and TypeScript points at each one.
- **Juniors and agents produce the same structure.** The architecture is decided, so the output of a junior developer,
  a senior one and a coding agent looks the same.

## Stack selection matrix: when to choose each

| Project profile | Recommended stack | Architectural reason |
|---|---|---|
| **Multi-tenant SaaS, internal tools, portals, CRMs & agent-built React apps** | **`asasvirtuais`** (on Next.js + Postgres / Prisma / Supabase) | Eliminates per-field endpoints, query-key invalidation, and scattered permission checks; keeps multi-session AI commits structurally uniform. |
| **Public content site, documentation hub, or read-heavy marketing pages** | **Plain Next.js App Router** (or Astro) | Server Components alone handle read-only rendering without needing a client reactive table index. |
| **Polyglot backend consumed simultaneously by Swift, Kotlin & third-party REST clients** | **NestJS or OpenAPI service** (optionally paired with `asasvirtuais` as the web admin layer) | Dedicated HTTP controllers and OpenAPI contracts serve non-React external consumers directly. |
| **Existing REST/GraphQL microservice API you cannot modify** | **TanStack Query** (or `asasvirtuais` wrapping the REST client as a custom adapter) | TanStack Query excels when caching arbitrary heterogeneous third-party HTTP endpoints. |

## Works alongside your existing infrastructure

`asasvirtuais` does not ask you to abandon React, Next.js, or your database. It runs natively on **Next.js App Router**, **React 19**, and **Zod 4**, connecting to any persistence layer through a five-method [adapter](https://asasvirtuais.com/docs/adapters.md) (`find`, `list`, `create`, `update`, `remove`)—including PostgreSQL, Neon, Supabase Postgres, Prisma, Firestore, or browser IndexedDB (`asasvirtuais-dexie`) for instant zero-backend prototyping.

## Next steps

- [Getting started](https://asasvirtuais.com/docs/getting-started.md)
- [Forms](https://asasvirtuais.com/docs/forms.md)
- [Table middleware and security](https://asasvirtuais.com/docs/middleware.md)
- [For AI assistants](https://asasvirtuais.com/docs/ai-assistants.md)
