Skip to content

Vet clinic (multi-tenant)

This tutorial builds examples/vet-clinic: a small SaaS for veterinary clinics. Each clinic is a tenant; staff, owners, pets, appointments, visits, and vaccinations are isolated by clinic.

We use --tenancy with a fresh starter instead of the ready-made saas template so you can see how to add the clinic-specific models and policies yourself. If you want a prebuilt organizations-and-projects demo instead, use the saas template described in Templates.

It is written for someone comfortable with JavaScript or TypeScript who is new to Dashild. Every step explains what the command or file does, not just what to paste.

What you will learn:

  • How a Prisma model becomes a Dashild resource.
  • How tenant isolation works on the server.
  • How roles decide which actions appear.
  • How relations, filters, custom cells, and action handlers fit together.

The finished app is in the repository if you want to compare.

Terminal window
pnpm create dashild@latest vet-clinic --tenancy --database sqlite --yes
cd vet-clinic

The scaffolder creates a Next.js app, installs Dashild, and prepares the panel. --tenancy adds the multi-tenant pieces:

  • An Organization model (one row per clinic).
  • User.organizationId and User.role.
  • src/lib/organization.ts: which clinics the user can see and which one is active.
  • src/lib/session.ts: getCurrentUser() returns the active clinic.
  • src/dashild/organization-actions.ts: the server action behind the switcher.
  • The mount route passes the clinics and the switcher to the panel.

--database sqlite keeps the example self-contained: the database is a file (prisma/dev.db), so you do not need a server.

BETTER_AUTH_URL must match the URL you open in the browser. The scaffold sets http://localhost:3000.

At this point pnpm dev already works, with an empty panel. We will fill it. The command starts Next.js in development mode. Keep that terminal open while you use the panel; stop the server with Ctrl+C.

prisma/schema.prisma describes the database tables. Prisma reads this file and generates a typed client; Dashild reads the generated metadata to know which fields a model has.

The tenancy setup already created Organization and the Role enum. Add VET and RECEPTION to the enum, and the back-relations that Prisma needs for the new tables:

prisma/schema.prisma
enum Role {
ADMIN
VET
RECEPTION
USER
}
model User {
// ...the Better Auth fields...
organizationId String?
organization Organization? @relation(fields: [organizationId], references: [id], onDelete: SetNull)
role Role @default(USER)
vetAppointments Appointment[] @relation("VetAppointments")
vetVisits Visit[] @relation("VetVisits")
}
model Organization {
id String @id @default(uuid())
name String
users User[]
owners Owner[]
pets Pet[]
appointments Appointment[]
visits Visit[]
vaccinations Vaccination[]
}

Then append the domain models:

prisma/schema.prisma
enum Species {
DOG
CAT
RABBIT
BIRD
OTHER
}
enum AppointmentStatus {
SCHEDULED
ATTENDED
CANCELLED
}
model Owner {
id String @id @default(uuid())
name String
email String?
phone String?
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
pets Pet[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([organizationId])
}
model Pet {
id String @id @default(uuid())
name String
species Species @default(DOG)
breed String?
birthDate DateTime?
photo Bytes?
ownerId String
owner Owner @relation(fields: [ownerId], references: [id], onDelete: Cascade)
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
appointments Appointment[]
visits Visit[]
vaccinations Vaccination[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([ownerId])
@@index([organizationId])
}
model Appointment {
id String @id @default(uuid())
startsAt DateTime
reason String
status AppointmentStatus @default(SCHEDULED)
petId String
pet Pet @relation(fields: [petId], references: [id], onDelete: Cascade)
vetId String?
vet User? @relation("VetAppointments", fields: [vetId], references: [id], onDelete: SetNull)
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([petId])
@@index([organizationId])
@@index([startsAt])
}
model Visit {
id String @id @default(uuid())
visitedAt DateTime @default(now())
reason String
diagnosis String?
notes String?
petId String
pet Pet @relation(fields: [petId], references: [id], onDelete: Cascade)
vetId String?
vet User? @relation("VetVisits", fields: [vetId], references: [id], onDelete: SetNull)
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([petId])
@@index([organizationId])
}
model Vaccination {
id String @id @default(uuid())
name String
appliedAt DateTime @default(now())
nextDueAt DateTime?
petId String
pet Pet @relation(fields: [petId], references: [id], onDelete: Cascade)
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
@@index([petId])
@@index([organizationId])
}

A few things to notice:

  • organizationId is repeated on the clinic data. It looks redundant, but it makes tenant filters and indexes simple and fast.
  • Pet.owner is a relation to Owner; Appointment.pet is a relation to Pet. Dashild uses those relations for columns, forms, and relation managers.
  • photo Bytes? stores the image in the database for this example. In a real app you would usually store a URL.

migrate dev compares the schema with the database, writes a migration, and applies it. It also regenerates the Prisma client and the Dashild metadata. The migration is a checked-in record of how the schema changed; its name is a short label so teammates can understand the change later.

Terminal window
pnpm prisma migrate dev --name vet_schema

Now create prisma/seed.ts. A seed is a script that inserts predictable demo data so the panel is not empty. This example’s seed first deletes its existing demo rows, then creates two clinics and test users so you can test switching. Use it only with this local demo database, not a database containing real data.

prisma/seed.ts
import "dotenv/config";
import { auth } from "../src/lib/auth";
import { prisma } from "../src/lib/prisma";
const PASSWORD = "dashild123";
async function createUser(input: {
email: string;
name: string;
role: "ADMIN" | "VET" | "RECEPTION";
organizationId: string;
}) {
const created = await auth.api.signUpEmail({
body: { email: input.email, password: PASSWORD, name: input.name },
});
if (!created.user) throw new Error(`Better Auth did not create ${input.email}`);
await prisma.user.update({
where: { id: created.user.id },
data: { role: input.role, organizationId: input.organizationId },
});
return created.user;
}
async function main() {
await prisma.vaccination.deleteMany();
await prisma.visit.deleteMany();
await prisma.appointment.deleteMany();
await prisma.pet.deleteMany();
await prisma.owner.deleteMany();
await prisma.session.deleteMany();
await prisma.account.deleteMany();
await prisma.user.deleteMany();
await prisma.organization.deleteMany();
const acme = await prisma.organization.create({ data: { name: "Clínica Acme" } });
const beta = await prisma.organization.create({ data: { name: "Clínica Beta" } });
const ana = await createUser({
email: "ana@acme.vet",
name: "Ana Torres",
role: "ADMIN",
organizationId: acme.id,
});
const victor = await createUser({
email: "victor@acme.vet",
name: "Víctor Salas",
role: "VET",
organizationId: acme.id,
});
await createUser({
email: "rita@acme.vet",
name: "Rita Gómez",
role: "RECEPTION",
organizationId: acme.id,
});
const carla = await createUser({
email: "carla@beta.vet",
name: "Carla Ruiz",
role: "VET",
organizationId: beta.id,
});
const lucia = await prisma.owner.create({
data: { name: "Lucía Fernández", organizationId: acme.id },
});
const nala = await prisma.pet.create({
data: {
name: "Nala",
species: "DOG",
ownerId: lucia.id,
organizationId: acme.id,
},
});
const milo = await prisma.pet.create({
data: {
name: "Milo",
species: "CAT",
ownerId: lucia.id,
organizationId: acme.id,
},
});
const hugo = await prisma.owner.create({
data: { name: "Hugo Santos", organizationId: beta.id },
});
const toby = await prisma.pet.create({
data: {
name: "Toby",
species: "DOG",
ownerId: hugo.id,
organizationId: beta.id,
},
});
await prisma.appointment.createMany({
data: [
{
startsAt: new Date(Date.now() + 86_400_000),
reason: "Revisión anual",
petId: nala.id,
vetId: victor.id,
organizationId: acme.id,
},
{
startsAt: new Date(Date.now() - 86_400_000),
reason: "Cojera leve",
status: "ATTENDED",
petId: milo.id,
vetId: victor.id,
organizationId: acme.id,
},
{
startsAt: new Date(Date.now() + 2 * 86_400_000),
reason: "Vacunación",
petId: toby.id,
vetId: carla.id,
organizationId: beta.id,
},
],
});
await prisma.visit.create({
data: {
reason: "Cojera leve",
diagnosis: "Esguince leve",
petId: milo.id,
vetId: victor.id,
organizationId: acme.id,
},
});
await prisma.vaccination.create({
data: {
name: "Rabia",
petId: nala.id,
organizationId: acme.id,
},
});
console.log("seed ready. login: ana@acme.vet / " + PASSWORD);
}
main()
.then(() => prisma.$disconnect())
.catch(async (error) => {
console.error(error);
await prisma.$disconnect();
process.exit(1);
});

Add the script to package.json. A package script gives the longer TypeScript command a short, repeatable name:

package.json
{
"scripts": {
"db:seed": "tsx prisma/seed.ts"
}
}
Terminal window
pnpm db:seed

pnpm db:seed runs that script. It can be run again to reset the demo data to the same starting state.

The example’s full seed has more owners, pets, visits, and vaccinations; it is linked at the end.

A resource is a data file. It says which model to show, which columns and form fields to use, and which policy protects it. Dashild has one route for every resource; there is no page to generate.

Terminal window
pnpm dashild make:resource Owner

The command takes the Prisma model name, singular: Owner, not Owners.

make:resource reads dashild-metadata.json, the file the Prisma generator writes, and:

  1. Writes src/dashild/resources/owner.ts with columns and form fields inferred from the model.
  2. Registers the resource in src/dashild/panel.ts.
  3. Adds a fail-closed entry to src/dashild/policies.ts (scope: () => null), so nothing is visible until you define the policy.

The file is write-once: running the command again does not overwrite your work.

Open the generated file and adjust it until it looks like this:

src/dashild/resources/owner.ts
import { defineResource } from "@dashild/core";
export const ownerResource = defineResource({
model: "Owner",
navigation: { label: "Owners", slug: "owners", group: "Clinic", icon: "users" },
table: {
searchable: ["name", "email", "phone"],
pageSize: 25,
columns: [
{ field: "name", sortable: true },
{ field: "email", sortable: true },
{ field: "phone" },
{ field: "createdAt", format: "datetime", sortable: true },
],
},
form: {
fields: [
{ field: "name", type: "text", rules: { required: true } },
{ field: "email", type: "email" },
{ field: "phone", type: "text" },
],
},
policy: { scope: "organization" },
});

searchable lists the fields used by the search box. policy: { scope: "organization" } is a marker: the actual filter lives in policies.ts, which we write in step 8.

The owners table

The first resource in the panel: search, sorting, pagination, and the create button all come from the definition above.

The rest follow the same command. Run them now:

Terminal window
pnpm dashild make:resource Pet
pnpm dashild make:resource Appointment
pnpm dashild make:resource Visit
pnpm dashild make:resource Vaccination
pnpm dashild make:resource User

Then customize each file. Pet and Appointment are explained below; Visit, Vaccination, and User follow the same shape and are linked at the end. The generated version is a starting point; columns, filters, and form fields are data you own.

Creating an owner

The form is built from form.fields; the server performs the final validation.

The pet resource you generated in step 5 needs a custom cell. The Pet model has a species column, but DOG/CAT is not friendly in a table. A cell is a small React component that renders one column value. The shell ships a few templates; copy one and adapt it instead of starting from scratch:

Terminal window
pnpm dashild ui:add avatar-cell --dir src/components/dashild

ui:add copies the template to src/components/dashild/ (the default folder is components/dashild, so --dir points it at the app’s src/ tree) and prints the registerCell(...) line you need. It does not edit the registry for you: the component name and import path are your decision.

Rename the copied file to species-cell.tsx and replace its content:

src/components/dashild/species-cell.tsx
"use client";
import type { CellRendererProps } from "@dashild/admin";
const SPECIES: Record<string, { label: string; emoji: string }> = {
DOG: { label: "Dog", emoji: "🐶" },
CAT: { label: "Cat", emoji: "🐱" },
RABBIT: { label: "Rabbit", emoji: "🐰" },
BIRD: { label: "Bird", emoji: "🐦" },
OTHER: { label: "Other", emoji: "🐾" },
};
/** Custom cell: species with an emoji instead of the raw enum value. */
export function SpeciesCell({ value }: CellRendererProps) {
const species = SPECIES[String(value)] ?? {
label: String(value ?? ""),
emoji: "🐾",
};
return (
<span className="inline-flex items-center gap-1.5">
<span aria-hidden="true">{species.emoji}</span>
{species.label}
</span>
);
}

Then register it. Registration happens on the client, because components are functions and cannot travel from a server component as props:

src/dashild/registry.tsx
"use client";
import {
registerCell,
registeredCells,
registeredFields,
} from "@dashild/core";
import { RegistryProvider, type Registry } from "@dashild/admin";
import { SpeciesCell } from "../components/dashild/species-cell";
registerCell("species", SpeciesCell);
export function AppRegistryProvider({ children }: { children: React.ReactNode }) {
return (
<RegistryProvider
cells={registeredCells() as Registry["cells"]}
fields={registeredFields() as Registry["fields"]}
>
{children}
</RegistryProvider>
);
}

Finally, use cell: "species" in the pet resource and include a photo field:

src/dashild/resources/pet.ts
import { defineResource } from "@dashild/core";
export const petResource = defineResource({
model: "Pet",
navigation: { label: "Pets", slug: "pets", group: "Clinic", icon: "layers" },
table: {
searchable: ["name", "breed"],
pageSize: 25,
columns: [
{ field: "name", sortable: true },
{ field: "species", cell: "species" },
{ field: "breed" },
{ field: "owner", display: "name", sortable: true },
{ field: "birthDate", format: "date", sortable: true },
],
filters: [
{ field: "species", type: "enum", label: "Species" },
{ field: "owner", type: "relation", label: "Owner", display: "name" },
],
},
form: {
fields: [
{ field: "name", type: "text", rules: { required: true } },
{ field: "species", type: "select" },
{ field: "breed", type: "text" },
{ field: "birthDate", type: "date" },
{
field: "owner",
type: "relation",
relation: "owner",
display: "name",
rules: { required: true },
},
{ field: "photo", type: "bytes" },
],
},
policy: { scope: "organization" },
});

{ field: "photo", type: "bytes" } tells the form to render a file picker and send the file as base64.

Pets with the custom species cell

The species column renders the registered cell: an emoji and a readable label instead of the raw DOG/CAT value.

Creating a pet

The species and owner fields are selects; the photo field is a file picker.

Editing a pet with the photo field

{ field: "photo", type: "bytes" } renders a file picker; the file travels as base64 and is stored in Bytes.

The appointment resource adds filters and actions:

src/dashild/resources/appointment.ts
import { defineResource } from "@dashild/core";
export const appointmentResource = defineResource({
model: "Appointment",
navigation: {
label: "Appointments",
slug: "appointments",
group: "Clinic",
icon: "calendar",
},
table: {
searchable: ["reason"],
pageSize: 25,
columns: [
{ field: "startsAt", format: "datetime", sortable: true },
{ field: "pet", display: "name", sortable: true },
{ field: "vet", display: "name" },
{ field: "reason" },
{
field: "status",
format: "badge",
tone: { SCHEDULED: "accent", ATTENDED: "green", CANCELLED: "danger" },
},
],
filters: [
{ field: "status", type: "enum", label: "Status" },
{ field: "pet", type: "relation", label: "Pet", display: "name" },
{ field: "vet", type: "relation", label: "Vet", display: "name" },
],
actions: [
{ name: "create", placement: "header" },
{ name: "view", placement: "row" },
{ name: "edit", placement: "row" },
{ name: "delete", placement: "row" },
{
name: "attend",
label: "Mark attended",
placement: "row",
requires: "attend",
variant: "secondary",
},
{
name: "cancelAppointment",
label: "Cancel",
placement: "row",
requires: "cancelAppointment",
variant: "destructive",
confirm: true,
},
],
},
form: {
fields: [
{ field: "startsAt", type: "datetime", rules: { required: true } },
{
field: "pet",
type: "relation",
relation: "pet",
display: "name",
rules: { required: true },
},
{
field: "vet",
type: "relation",
relation: "vet",
display: "name",
},
{ field: "reason", type: "text", rules: { required: true } },
{ field: "status", type: "select" },
],
},
policy: { scope: "organization" },
});

Two rules matter here:

  • Declaring table.actions replaces the built-in create/view/edit/delete actions, so the resource lists them explicitly and then adds its own.
  • Do not name a custom action cancel: it is a built-in form action and the panel would ignore yours. The example uses cancelAppointment.

filters renders the bar above the table. Options for status come from the Prisma enum; options for pet and vet are loaded on the server and scoped to the active clinic.

Appointments with filters

Status, pet, and vet filters are resolved on the server and scoped to the active clinic.

Appointment row actions

The declared actions appear in the row menu. The policy decides which roles see “Mark attended” and “Cancel”.

make:resource added a fail-closed entry for every model. Replace policies.ts with the real rules:

src/dashild/policies.ts
import {
definePolicies,
hasRole,
type CurrentUser,
} from "@dashild/core";
const orgScope = (ctx: { organizationId: string | null }) =>
ctx.organizationId ? { organizationId: ctx.organizationId } : null;
const admin = (ctx: { roles: string[] }) => hasRole(ctx, "ADMIN");
const clinical = (ctx: { roles: string[] }) =>
hasRole(ctx, "ADMIN", "VET");
const staff = (ctx: { roles: string[] }) =>
hasRole(ctx, "ADMIN", "VET", "RECEPTION");
/**
* Every resource is scoped to the active clinic. A session without an
* organization (for example, right after sign-up) sees nothing.
*/
export const policies = definePolicies<CurrentUser>({
resources: {
Owner: {
scope: orgScope,
can: { create: staff, update: staff, delete: admin },
},
Pet: {
scope: orgScope,
can: { create: staff, update: staff, delete: admin },
},
Appointment: {
scope: orgScope,
can: {
create: staff,
update: staff,
delete: admin,
attend: clinical,
cancelAppointment: (ctx) => hasRole(ctx, "ADMIN", "RECEPTION"),
},
},
Visit: {
scope: orgScope,
can: { create: clinical, update: clinical, delete: admin },
},
Vaccination: {
scope: orgScope,
can: { create: clinical, update: clinical, delete: admin },
},
User: {
scope: orgScope,
can: { create: () => false, update: admin, delete: () => false },
},
},
});

How to read it:

  • scope is a Prisma where applied on the server to scoped reads, updates, and deletes, plus the panel’s relation managers. It does not constrain create/createMany, and included relation rows are not filtered by their own policy. Returning null denies the resource, so a session without a clinic sees nothing. Create permissions and the new row’s organizationId must be handled explicitly.
  • can decides permissions. ADMIN, VET, and RECEPTION are strings that come from User.role; the app defines them.
  • Declared actions (attend, cancelAppointment) are deny-by-default: if the predicate is missing, the action is hidden and the server refuses it.

The staff table

The same User model is a normal resource; the policy allows admins to update roles and hides create/delete.

Important for tenant-owned inserts: this policy grants create permission, but the generic resource form does not infer or fill organizationId from scope. In a real app, keep tenant-owned create disabled until you provide a server-side create flow that assigns the active clinic from the authenticated session. Never accept that ownership id from an editable browser field. The seeded records let you explore the rest of this tutorial without relying on that unfinished create flow.

The resource declares the action; the handler runs on the server:

src/dashild/actions/index.ts
import type { ActionHandler, CurrentUser } from "@dashild/core";
type AppointmentStatus = "ATTENDED" | "CANCELLED";
interface ScopedAppointmentClient {
appointment: {
update(args: {
where: { id: string };
data: { status: AppointmentStatus };
}): Promise<unknown>;
};
}
async function setStatus(
context: Parameters<ActionHandler<CurrentUser>>[0],
status: AppointmentStatus,
) {
if (!context.id) {
return { ok: false, message: "Missing appointment id." };
}
const db = context.db as ScopedAppointmentClient | undefined;
if (!db) {
return { ok: false, message: "Database client unavailable." };
}
await db.appointment.update({
where: { id: context.id },
data: { status },
});
return {
ok: true,
message:
status === "ATTENDED"
? "Appointment marked as attended."
: "Appointment cancelled.",
};
}
/**
* Handlers run on the server with the scoped Prisma client, so an appointment
* from another clinic is not reachable even if the id is guessed.
*/
export const resourceActions: Record<
string,
Record<string, ActionHandler<CurrentUser>>
> = {
Appointment: {
attend: (context) => setStatus(context, "ATTENDED"),
cancelAppointment: (context) => setStatus(context, "CANCELLED"),
},
};

The db in the context is Prisma extended with the policy scope. An appointment from another clinic is not reachable even if someone guesses its id.

The shell has 19 built-in icons. The vaccination resource uses shield, which is not one of them, so install an icon set and register it:

Terminal window
pnpm add lucide-react
src/dashild/icons.tsx
"use client";
import type { ElementType } from "react";
import { IconProvider } from "@dashild/admin";
import { Shield } from "lucide-react";
/**
* App icon registry.
*
* Add any React icon component here under the name used by
* `navigation.icon` or `action.icon`.
*/
export const icons: Record<string, ElementType> = {
shield: Shield,
};
export function AppIconProvider({ children }: { children: React.ReactNode }) {
return <IconProvider icons={icons}>{children}</IconProvider>;
}
Terminal window
pnpm dev

Open http://localhost:3000/admin and sign in:

Email Role Clinic
ana@acme.vet ADMIN Clínica Acme
victor@acme.vet VET Clínica Acme
rita@acme.vet RECEPTION Clínica Acme
carla@beta.vet VET Clínica Beta

Password: dashild123.

The clinic dashboard

Every registered resource appears in the sidebar, grouped by navigation.group.

What to check:

  1. As Ana, switch between Acme and Beta in the sidebar. Lists, form options, and relation managers follow the active clinic.
  2. As Víctor (VET), “Mark attended” appears on appointments; “Cancel” does not.
  3. As Rita (RECEPTION), “Cancel” appears and asks for confirmation.
  4. As Carla, only Beta exists.
  5. Filter pets by species and appointments by status.
  6. Open an owner to see their pets; open a pet for visits and vaccinations.

The clinic switcher

Ana belongs to both clinics. The switcher is validated on the server; the cookie alone cannot grant access to another tenant.

The Beta dashboard

The header, lists, and form options now use Clínica Beta. Switching back to Acme restores its data.

Beta only shows its own data

After switching, the owners list contains only Hugo Santos. The same policy scope applies to lists, form options, and relation managers.

Beta pets

The pets list follows the active clinic too: Beta only has Toby.

The remaining resources are generated and edited the same way. Copy them from the repository:

  • init refuses tenancy: it needs a schema without auth models. Start from a fresh scaffold or add the organization fields by hand.
  • Empty lists: every policy returns null without an organization. Check that the user has one and that the switcher shows a clinic.
  • Missing custom action: the name collides with a built-in (cancel, delete, save…). Rename it.
  • Prisma types out of date: run pnpm prisma generate after every schema change.