Quickback Docs
Scoped Database

Sharing Code Between Actions

Import tables and helpers across actions, and use executor parameters — auth, whereRecord, ctx.auth, ctx.unmask and authDb.

Share tables and helpers between actions without losing the security filters, and use the parameters every executor receives. Start at Scoped Database for the db handle.

Sharing Code Between Actions

For Zod schemas, helpers, or constants used across multiple actions in a feature, put them under <feature>/lib/ and import from each action file. Files under lib/ are copied verbatim into the generated output.

features/applications/
├── applications.ts
├── actions/
│   ├── advance.ts
│   └── reject.ts
└── lib/
    ├── inputs.ts          ← shared Zod schemas
    └── transitions.ts     ← state-machine helpers
// features/applications/lib/inputs.ts
import { z } from "zod";

export const advanceInput = z.object({
  nextStatus: z.enum(["screening", "interview", "offer"]),
  notes: z.string().max(2000).optional(),
});
// features/applications/actions/advance.ts
import { defineAction } from "../.quickback/define-action";
import { advanceInput } from "../lib/inputs";

export default defineAction({
  description: "Move forward",
  input: advanceInput,
  access: { roles: ["owner"] },
  async execute({ db, record, input }) { /* … */ },
});

Importing Tables

The action's own generated helper supplies defineAction and the tables owned by that feature. It does not re-export tables from sibling features. Import a cross-feature table from that feature's generated helper or generated table module, and import Drizzle query operators through the generated project lib/q:

// features/waitlist/actions/promote.ts
import {
  defineAction,
  waitlistEntries,
} from "../.quickback/define-action";
import { reservations } from "../../reservations/.quickback/define-action";
import { q } from "../../../lib/q";

export default defineAction({
  // ...input, access, and transition...
  async execute({ db, record, whereRecord, now }) {
    const existing = await db
      .select()
      .from(reservations)
      .where(q.eq(reservations.waitlistEntryId, record.id));

    await db
      .update(waitlistEntries)
      .set({ promotedAt: now })
      .where(whereRecord!(waitlistEntries));

    return existing;
  },
});

Path pattern from features/{name}/actions/:

  • Own feature helper: ../.quickback/define-action
  • Other feature helper: ../../{other-feature}/.quickback/define-action
  • Other generated table module: ../../{other-feature}/{table-file-name}
  • Generated project query helper: ../../../lib/q
  • Other generated lib files: ../../../lib/{module} (for example, ../../../lib/realtime or ../../../lib/webhooks)

Keep defineAction from the action's own feature: that helper binds record, whereRecord, and whereTransition. Import only the external table from a sibling feature. The waitlist/reservations names above are just the common pattern; the rule applies to every cross-feature action.

Executor Parameters

import type { Auth } from "better-auth";

interface ActionExecutorParams {
  db: DrizzleDB;           // Scoped database (auto-applies org/owner/soft-delete filters)
  unsafeDb?: DrizzleDB;    // Unscoped database (only available when unsafe mode is enabled)
  target?: TRow;          // The loaded operator target (operator lane only — see Operator lane)
  ctx: AppContext;         // User context (userId, roles, activeOrgId, activeTeamId, userRole)
  record?: TRecord;        // The record (record-based only, undefined for standalone)
  input: TInput;           // Validated input from Zod schema
  services: TServices;     // Configured integrations (billing, notifications, etc.)
  c: HonoContext;          // Raw Hono context for advanced use
  env: Env;                // Runtime bindings (Cloudflare env / process env). Alias for c.env.
  auth: Auth;              // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.
  whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.
  whereTransition?: (table) => SQL; // whereRecord plus the transition's "from" precondition. Transition actions only.
  page?: QbActionPage;     // Keyset page helper over the scoped db. Only when the action declares `pagination:` — see Paginated actions.
}

auth — Better Auth instance

auth is the Better Auth instance, ready to call from inside an action handler. Use it for things like minting an OAuth access token, fetching the current session in a custom way, or invoking a Better Auth plugin method that isn't already exposed by the generated middleware.

// features/integrations/actions/connectGoogleDrive.ts
import { defineAction } from "../.quickback/define-action";
import { z } from "zod";

export default defineAction({
  description: "Get a fresh Google Drive access token for the signed-in user",
  input: z.object({}),
  access: { roles: ["AUTHENTICATED"] },
  async execute({ auth, ctx, c }) {
    // genericOAuth plugin method — needs a cast since the default-generic
    // `Auth` type doesn't carry plugin-specific API surface.
    const token = await (auth.api as any).getAccessToken({
      headers: c.req.raw.headers,
      body: { providerId: "google", userId: ctx.userId },
    });
    return { accessToken: token.accessToken };
  },
});

Lazy on Cloudflare: the generated handler emits a Proxy so createAuth(c.env, c.req.raw.cf) only runs the first time you read a property on auth. Actions that never touch auth pay zero construction cost. On Bun/Node auth is the imported singleton (an IIFE that lazy-loads the database adapter) wrapped in the same proxy shape — call sites are identical across runtimes.

Typing: auth is typed as Auth from better-auth. The base API (getSession, signOut, signInEmail, etc.) is fully typed. Plugin-only methods (getAccessToken from genericOAuth, admin-plugin methods, etc.) need a cast at the call site — the default-generic Auth doesn't infer the project's specific plugin set.

whereRecord — explicit, scope-safe WHERE

For protected-field writes inside record-based actions, prefer whereRecord(table) over eq(table.id, record.id). It returns a Drizzle expression that AND-merges the resource's firewall and soft-delete predicates with the record id, so the WHERE is explicit even if a future refactor swaps db back to an unscoped client:

// features/applications/actions/advance.ts
import { z } from "zod";
import { defineAction, applications } from "../.quickback/define-action";

export default defineAction({
  description: "Advance an application to the next status.",
  input: z.object({
    nextStatus: z.string(),
    notes: z.string().optional(),
  }),
  access: { roles: ["owner"] },
  async execute({ db, record, input, whereRecord }) {
    const [updated] = await db
      .update(applications)
      .set({
        status: input.nextStatus,
        notes: input.notes ?? record.notes,
      })
      .where(whereRecord!(applications))   // firewall + soft-delete + id, all in one
      .returning();
    return updated;
  },
});

The audit DB wrapper hard-stamps modifiedAt/modifiedBy on every .set() call, so handlers don't write them. The same wrapper hard-stamps createdAt/createdBy/modifiedAt/modifiedBy on every .values() — and on the conflict branch of an onConflictDoUpdate({...}) upsert. Caller-supplied audit fields are dropped on the floor — the audit log always reflects the real actor and the real moment.

Who the stamped actor is depends on the verified principal, never on anything the handler passes:

CallercreatedBy / modifiedBy value
Signed-in userthe Better Auth userId
Delegated principal (API key, service)actor:<type>:<id>
Cron schedule via withInternalContextsystem:cron-<name>
Queue handler via withInternalContextsystem:queue-<name>
No verified callerthe write throws (fail closed) — system-side code that must write outside a request uses the raw client and owns its own provenance

Don't hand-build audit timestamps as a "just in case" fallback: on the wrapped db they're dead code, and the idiom is a portability trap — Postgres audit columns take Date objects while SQLite takes ISO strings (the wrapper picks the right one per dialect).

whereRecord is undefined for standalone actions (they have no record), so the parameter is typed as optional. whereTransition extends whereRecord with the transition's "from" precondition for transition actions.

ctx.auth — Better Auth users and members, org-bound

Changing a user — banning them, changing their role, deleting the account — through a raw authDb handle bypasses the revocation stamps used to invalidate outstanding JWTs. Use ctx.auth instead. It is hydrated on every request context in Cloudflare + Better Auth projects and typed on execute's ctx:

// features/guests/actions/banMember.ts
import { z } from "zod";
import { defineAction } from "../.quickback/define-action";

export default defineAction({
  description: "Ban a member of the active organization.",
  path: "/members/ban",
  input: z.object({ userId: z.string(), reason: z.string().optional() }),
  access: { roles: ["owner", "admin"] },
  async execute({ ctx, input }) {
    await ctx.auth.ban(input.userId, input.reason);
    return { banned: input.userId };
  },
});
MethodRequiresDoes
ctx.auth.ban(userId, reason?)admin pluginSets banned + banReason, deletes every session. You cannot ban yourself.
ctx.auth.setRole(userId, role, { orgId? })organization pluginSets the member's role in the active organization (role is typed to the declared organization roles). The last owner cannot be demoted (409).
ctx.auth.deleteAccount(userId)—Deletes the user's memberships, sessions, linked accounts, then the user. Deleting yourself is always allowed.
ctx.auth.members.list(orgId?)organization pluginThe organization's members: { id, userId, organizationId, role, createdAt, user: { id, email, name, image } }.
ctx.auth.claims.backfill(opts?)auth.claimsLinks rows that predate their account.

Every method writes through Better Auth's adapter with its schema mapping. setRole adds a database-enforced guard to that adapter update so concurrent calls cannot both demote the remaining owners; PostgreSQL calls serialize per organization. A stale membership or target platform-role read also fails with 409 AUTH_SURFACE_LAST_OWNER, so reload before retrying. Organization endpoint lifecycle hooks are not invoked by this action surface; account methods use Better Auth's internal adapter where applicable. With auth.jwt.revocationCheck: 'kv' each write stamps qbrev:user:<id> (and qbrev:member:<id>:<org> for a role change), so outstanding JWTs die within seconds; if the stamp cannot be written the method throws 503 AUTH_REVOCATION_UNAVAILABLE instead of reporting success. Platform roles (user.role) are not ctx.auth's job: change them with Better Auth's /admin/set-role, which is on the revocation kill list too.

Who may act on whom. The action's access decides who can call it; ctx.auth then bounds what the call can touch:

  • An operator — a caller whose platform role is one of the admin plugin's adminRoles (appmanager, sysadmin by default) — may act on any user whose platform role ranks at or below its own, and may name another organization (orgId).
  • Everyone else is org-bound. The target must be a member of the caller's active organization (otherwise 404 AUTH_SURFACE_NOT_FOUND — nothing is learned about other tenants' users), must hold an organization role at or below the caller's (auth.roleHierarchy, default member < admin < owner), and must not be an operator. setRole may not assign a role above the caller's own. ban and deleteAccount change the whole account, so they also refuse a target who belongs to any other organization.

Errors are action errors: 401 AUTH_SURFACE_UNAUTHENTICATED (no account caller), 403 AUTH_SURFACE_NO_ORG, 403 AUTH_SURFACE_OUT_OF_SCOPE, 403 AUTH_SURFACE_ROLE_CEILING, 400 AUTH_SURFACE_INVALID_ROLE, 400 AUTH_SURFACE_SELF, 404 AUTH_SURFACE_NOT_FOUND, 409 AUTH_SURFACE_LAST_OWNER, 503 AUTH_REVOCATION_UNAVAILABLE.

ctx.unmask — reading a q.secret() column

A q.secret() column is never returned by any read path, and the rows your action reads hold its ciphertext. ctx.unmask(row, column) is the one server-side read: it decrypts with the row's own organization key and records a best-effort masked_reveal audit entry.

// features/integrations/actions/checkSecret.ts
import { z } from "zod";
import { defineAction } from "../.quickback/define-action";

export default defineAction({
  description: "Check an integration's client secret without revealing it.",
  input: z.object({ candidate: z.string() }),
  access: { roles: ["admin+"] },
  async execute({ ctx, record, input }) {
    const secret = await ctx.unmask(record, "clientSecret");
    return { matches: secret === input.candidate };
  },
});

column is the property name when no other table has a secret column of that name, or { table, column } (SQL table name + property name) — always accepted, and required for a shared name. The row must carry the column and its organization column; null unmasks to null.

On a tenant table (tenancy.isolation: 'durable-object') the same call opens the value with the tenant data key the edge carried on the request. A value written in plaintext before the column became q.secret() is returned as is; see Encrypted columns in tenant tables for the one-off re-encrypt.

Reaching Better Auth tables (authDb)

The scoped db is the features database. Better Auth tables never appear on it — that is by design. AUTH_DB is a separate Drizzle client.

Changing a user or member — use ctx.auth, never a write on authDb. A raw write skips Better Auth's hooks and leaves the user's JWTs alive.

Caller identity — use ctx, do not query AUTH_DB. ctx.userId, ctx.activeOrgId, ctx.roles, and ctx.userRole are already on the request.

To check that a submitted user id is an org member (assignee-style features), use c.get("authDb") plus the generated getOrgMemberRole helper:

// features/projects/actions/assign.ts — validate a userId is an org member
import { z } from "zod";
import { eq } from "drizzle-orm";
import { ActionError } from "@quickback/compiler";
import { defineAction, projects } from "../.quickback/define-action";
import { getOrgMemberRole } from "../../../lib/org-access";

export default defineAction({
  description: "Assign a project to an org member",
  input: z.object({ assigneeId: z.string() }),
  access: { roles: ["member", "admin"] },
  async execute({ db, record, input, ctx, c, whereRecord }) {
    // getOrgMemberRole(authDb, userId, organizationId) → role string | null
    const role = await getOrgMemberRole(c.get("authDb"), input.assigneeId, ctx.activeOrgId!);
    if (!role) {
      throw new ActionError("Assignee is not a member of this organization", "NOT_A_MEMBER", 400);
    }
    const [updated] = await db
      .update(projects)
      .set({ assigneeId: input.assigneeId })
      .where(whereRecord!(projects))
      .returning();
    return updated;
  },
});

c.get("authDb") is the Drizzle connection to the auth database (in dual-DB mode it's a separate D1 from your features). That is the native membership check.

On a single-database project — Postgres, or D1 without split databases — it is the same database as your features. On Postgres it runs under the caller's claims, so Better Auth's own RLS applies: members rows of the active organization are readable, users only the caller's own row. To list the active organization's members with names and emails, use the generated roster read.

For a richer query, use the same authDb and import tables from ../../../auth/schema — from an actions/ file. On D1 the tables are user, organization, and member — not organization_membership. (Neon exports the Better Auth CLI's plural names: users, organizations, members.)

SurfaceAUTH_DB handleNotes
Action executec.get("authDb")Import schema from ../../../auth/schema
Account hooks{ authDb, authSchema } injectedUse the injected namespace — do not invent a path to auth/schema
Trigger handler:noneArgs are { ctx, db, env } — db is features only. There is no c. Prefer ctx for the acting user. Do not import ../../auth/schema from the table file to reach AUTH_DB; that path used to compile and then fail package-mode wrangler. Check another user's membership in an action.

On this page