# Dashild documentation (full text) Source: https://dashild.vercel.app Skill: pnpm dashild skill install Generated from apps/docs/src/content/docs (English pages). --- # Blog (author scoping) Source: https://dashild.vercel.app/examples/blog/ This tutorial builds [examples/blog](https://github.com/dashild/dashild/tree/main/examples/blog): an editorial admin with posts, categories, tags, comments, and two roles. Authors only see and edit their own posts; administrators moderate everything. The `blog` starter writes the schema, resources, policies, actions, and seed. This guide explains every piece and shows the running app. It assumes you are comfortable with JavaScript or TypeScript and new to Dashild. What you will learn: - How to model a post with an enum, a many-to-many relation, and a `Bytes` cover. - How `scope` turns one resource into “my posts” for an author and “all posts” for an admin. - How role-aware policies hide and refuse actions. - How declared actions update `status` and `publishedAt` together. - How comments inherit the post's author scope. - How CSV import/export respects the active scope. The finished app is in the repository if you want to compare. ## 1. Create the app ```bash pnpm create dashild@latest my-blog --template blog --database sqlite --yes cd my-blog ``` The `blog` starter adds: - `Category`, `Tag`, `Post`, and `Comment` models, plus a `Role` enum and `User.role`. - One resource per model under `src/dashild/resources/`. - `src/dashild/policies.ts`, `src/dashild/actions/index.ts`, and the panel registration. - A replacement `src/lib/session.ts` that returns the user's role. The starter lists it in `overwrite`, so it replaces the generated session file instead of being ignored. - A seed with an admin, two authors, posts, tags, and comments. `--database sqlite` keeps the example self-contained (`prisma/dev.db`). `BETTER_AUTH_URL` must match the URL you open. Change it if you use another port: ```bash BETTER_AUTH_URL=http://localhost:3001 pnpm dev ``` ![Sign in to the blog panel](/images/examples/blog/login.png) *The panel uses the same Better Auth login; the demo users have different roles.* ## 2. The data model The blog adds a role and an editorial workflow to the Better Auth models: ```prisma title="prisma/schema.prisma" enum Role { ADMIN AUTHOR } enum PostStatus { DRAFT REVIEW PUBLISHED } model Post { id String @id @default(uuid()) title String slug String @unique excerpt String? body String status PostStatus @default(DRAFT) publishedAt DateTime? cover Bytes? authorId String author User @relation(fields: [authorId], references: [id], onDelete: Cascade) categoryId String? category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull) tags Tag[] comments Comment[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } model Comment { id String @id @default(uuid()) authorName String body String approved Boolean @default(false) postId String post Post @relation(fields: [postId], references: [id], onDelete: Cascade) createdAt DateTime @default(now()) } ``` What matters for the admin: - **`authorId`** is the ownership field. The policy scopes every query by it. - **`status`** is an enum rendered as a badge. `publishedAt` is separate: an action sets both together. - **`tags`** is a many-to-many relation. The form renders a multi-select and the relation manager uses attach/detach. - **`cover`** is `Bytes?`; the form renders a file picker and sends base64. - **`Comment.postId`** is required and cascades. A comment cannot exist without its post, and deleting a post deletes its comments. `User.role` is a plain Prisma enum. `session.ts` reads it and returns `roles: ["ADMIN"]` or `roles: ["AUTHOR"]`, which is the shape every policy receives. ## 3. Create the database and seed it ```bash pnpm prisma migrate dev --name init pnpm prisma generate pnpm db:seed ``` `migrate dev` writes the migration, but on Prisma 7 it does **not** regenerate the Dashild metadata. Run `prisma generate` before opening the panel or using `make:resource`. The seed creates: | Email | Role | Password | | --- | --- | --- | | `ana@blog.test` | ADMIN | `dashild123` | | `bruno@blog.test` | AUTHOR | `dashild123` | | `carla@blog.test` | AUTHOR | `dashild123` | It also creates two categories, four tags, three posts, and two comments. Bruno owns two posts; Carla owns one. The published post has one approved and one pending comment. `pnpm db:seed` is re-runnable: it deletes comments, posts, tags, categories, and users in dependency order, then recreates them. ## 4. The panel and its resources The panel registers five resources: ```ts title="src/dashild/panel.ts" export const panel = definePanel({ title: "Admin", path: "/admin", locale: "en", resources: [ postResource, categoryResource, tagResource, commentResource, staffResource, ], auth: { getCurrentUser, signOut }, }); ``` They appear in three groups: - **Content**: Posts, Categories, Tags. - **Moderation**: Comments. - **Settings**: Staff. ![The blog dashboard](/images/examples/blog/dashboard.png) *A resource is one file of data. The catch-all route renders lists, forms, details, and relation managers from these definitions.* ## 5. Posts: the table and the form `src/dashild/resources/post.ts` is the center of the app: ```ts title="src/dashild/resources/post.ts" export const postResource = defineResource({ model: "Post", navigation: { label: "Posts", slug: "posts", group: "Content", icon: "file-text" }, table: { searchable: ["title", "excerpt"], pageSize: 25, columns: [ { field: "title", label: "Title", sortable: true }, { field: "status", label: "Status", format: "badge", tone: { DRAFT: "muted", REVIEW: "accent", PUBLISHED: "green" }, }, { field: "category", label: "Category", display: "name", sortable: true }, { field: "author", label: "Author", display: "name", sortable: true }, { field: "publishedAt", label: "Published", format: "datetime", sortable: true }, ], filters: [ { field: "status", type: "enum", label: "Status" }, { field: "category", type: "relation", label: "Category", display: "name" }, { field: "author", type: "relation", label: "Author", display: "name" }, ], actions: [ { name: "create", placement: "header" }, { name: "view", placement: "row" }, { name: "edit", placement: "row" }, { name: "delete", placement: "row" }, { name: "publish", label: "Publish", placement: "row", requires: "publish", variant: "secondary" }, { name: "unpublish", label: "Unpublish", placement: "row", requires: "unpublish", confirm: true }, ], }, form: { fields: [ { field: "title", type: "text", rules: { required: true } }, { field: "slug", type: "text", rules: { required: true } }, { field: "excerpt", type: "textarea" }, { field: "body", type: "textarea", rules: { required: true } }, { field: "status", type: "select" }, { field: "publishedAt", type: "datetime" }, { field: "author", type: "relation", relation: "author", display: "name", rules: { required: true } }, { field: "category", type: "relation", relation: "category", display: "name" }, { field: "tags", type: "relation", relation: "tags", display: "name", multiple: true }, { field: "cover", type: "bytes" }, ], }, policy: { scope: "author" }, }); ``` ![The posts table](/images/examples/blog/posts-admin.png) *An admin sees every post. The status badge has a tone per enum value, and the filters are server-side.* ![Creating a post](/images/examples/blog/post-create.png) *The create form starts empty but already includes the author, category, tags, and cover fields.* ![Editing a post](/images/examples/blog/post-edit.png) *The form includes the relation select for author and category, the multi-select for tags, and a file picker for the cover.* `policy.scope: "author"` is a marker, not the rule. The actual predicate is in `policies.ts`; the string only signals that the resource is scoped. ## 6. Author scoping Open `src/dashild/policies.ts`: ```ts title="src/dashild/policies.ts" const isAdmin = (ctx: { roles: string[] }) => hasRole(ctx, "ADMIN"); export const policies = definePolicies({ resources: { Post: { scope: (ctx) => (isAdmin(ctx) ? {} : { authorId: ctx.user.id }), can: { create: () => true, update: () => true, delete: isAdmin, publish: () => true, unpublish: () => true, }, }, Comment: { scope: (ctx) => isAdmin(ctx) ? {} : { post: { authorId: ctx.user.id } }, can: { create: () => true, update: () => true, delete: isAdmin, approve: () => true, unapprove: () => true, }, }, User: { scope: () => ({}), can: { create: () => false, update: isAdmin, delete: () => false }, }, }, }); ``` `scope` returns a Prisma `where` that the server applies to reads, updates, deletes, and relation managers. For an admin it is `{}` (all rows); for an author it is `{ authorId: user.id }`. ![Bruno only sees his own posts](/images/examples/blog/posts-author.png) *Signed in as Bruno (AUTHOR), the same resource returns two posts instead of three. The rows are filtered on the server, not hidden in the browser.* `create` and `update` are value-aware: an author can only attribute a post to themselves. The `User.scope` for non-admins is `{ id: user.id }`, so the author select and the staff list only show their own account. Admins keep `{}` and can assign any author. Comments are scoped through the relation: `{ post: { authorId: user.id } }`. An author can moderate comments on their own posts but cannot reach a comment on someone else's post, even with a guessed id. Only admins can create or edit comments in the panel, so `approved` cannot be forged there; authors still use the approve action for their own posts. The `can` block is deny-by-default for declared actions: if `publish` or `approve` is missing, the action disappears from the UI and the server refuses it. Authors can delete neither posts nor comments in this example; only admins can. ## 7. Actions: publish, unpublish, approve The resource declares the action; the handler runs on the server: ```ts title="src/dashild/actions/index.ts" Post: { publish: (context) => setPostStatus(context, "PUBLISHED"), unpublish: (context) => setPostStatus(context, "DRAFT"), }, Comment: { approve: (context) => setCommentApproved(context, true), unapprove: (context) => setCommentApproved(context, false), }, ``` `setPostStatus` updates two fields so the data stays consistent: ```ts title="src/dashild/actions/index.ts" await db.post.update({ where: { id: context.id }, data: { status, publishedAt: status === "PUBLISHED" ? new Date() : null, }, }); ``` ![Post row actions](/images/examples/blog/post-actions.png) *“Publish” and “Unpublish” come from `table.actions`; unpublish confirms first.* ![Comment moderation](/images/examples/blog/comments.png) *Comments show the approved flag, the post, and the author name.* ![Comment row actions](/images/examples/blog/comment-actions.png) *“Approve” and “Unapprove” are normal actions. The handler runs with the scoped client, so an author cannot approve a comment on another author's post.* `context.db` is Prisma extended with the policy scope. It is typed `unknown` and can be `undefined`, so the example narrows it with `dbFrom`. `context.id` is optional; check it before a row action. ## 8. Staff and roles `src/dashild/resources/staff.ts` manages `User`: ```ts title="src/dashild/resources/staff.ts" export const staffResource = defineResource({ model: "User", navigation: { label: "Staff", slug: "staff", group: "Settings", icon: "users" }, table: { searchable: ["name", "email"], columns: [ { field: "name", sortable: true }, { field: "email", sortable: true }, { field: "role", format: "badge", tone: { ADMIN: "accent", AUTHOR: "muted" }, }, ], filters: [{ field: "role", type: "enum", label: "Role" }], }, form: { fields: [ { field: "name", type: "text", rules: { required: true } }, { field: "role", type: "select" }, ], }, policy: { scope: "public" }, }); ``` ![The staff table](/images/examples/blog/staff.png) *The role badge is another enum column. The policy hides create/delete from everyone and allows updates only for admins.* There is a subtlety: `session.ts` returns `roles` from `User.role`, but the panel reads the role from the database on every request. If an admin changes a user's role, that user gets the new permissions on their next request. The demo does not need to sign out and back in. ## 9. CSV import and export The list buttons are available on every resource and respect the active scope: - An admin exports all posts. - An author exports only their own posts. - The same predicates apply to import, so an author cannot create a post for someone else by sending an `authorId`. Rules: - **Export** uses the current search, filters, sort, and page size, capped at 5,000 rows. Relation columns export ids, and `Bytes` columns (the cover) are excluded. - **Import** is create-only, capped at 1,000 rows and 2 MB. Headers must match `form.fields`; unknown columns are ignored. - **Types**: `Int`/`Float` are coerced, booleans accept `true`/`1`, and `Decimal`/`BigInt` stay strings. - **Relations** use the form field name (`author`, `category`) with the id as the value, not the display name. The basic CSV path does not import many-to-many `tags`; use the form or the relation manager for those. Advanced import mapping and updates are reserved for Dashild Pro. ## 10. Run it and try ```bash pnpm dev ``` Open [http://localhost:3000/admin](http://localhost:3000/admin). As `ana@blog.test` (ADMIN): 1. See all three posts, filter by status or author. 2. Publish the draft, then unpublish it. The status and `publishedAt` change together. 3. Open **Comments** and approve the pending comment. 4. Open **Staff** and change a user's role. Sign out and sign in as `bruno@blog.test` (AUTHOR): 1. The posts list now shows only Bruno's two posts. 2. He can create and edit his posts and publish them. 3. He sees comments only on his posts; Carla's post is not reachable. 4. He cannot delete a post or change a role. Finally: ```bash pnpm dashild doctor pnpm build ``` ## 11. Extend it Add a model the same way as any Dashild app: ```bash pnpm prisma migrate dev --name add_series pnpm prisma generate pnpm dashild make:resource Series ``` Then edit the generated resource, add predicates to `policies.ts`, and run `pnpm dashild doctor`. `make:action Series feature` appends a handler stub without touching the resource. For the full resource-by-resource workflow from an empty app, read the [vet clinic tutorial](/examples/vet-clinic/). For policies and scope in depth, read the [policies guide](/guides/policies/). ## Troubleshooting - **An author sees every post**: the `Post.scope` branch is returning `{}`; check `session.ts` returns `roles` and that `hasRole` receives `"ADMIN"` only for admins. - **Publish is missing**: the `publish` predicate is absent from `can`, or the action name collides with a built-in. - **Comments are empty for an author**: the `Comment.scope` path expects `post.authorId`; a comment whose post has no author will not match. - **`make:resource` cannot find the model**: run `pnpm prisma generate` after `migrate dev`. - **Cover upload fails**: `Bytes` fields are excluded from CSV; use the form. --- # Examples Source: https://dashild.vercel.app/examples/ The examples below are runnable applications, not fixtures. They live outside the pnpm workspace so they install the published `@dashild/*` packages like a user's app. Each one has a full tutorial and seeded demo data. | Example | What it shows | | --- | --- | | [Vet clinic](/examples/vet-clinic/) | Multi-tenancy, roles, relations, actions, filters, a custom cell | | [Shop](/examples/shop/) | Decimal money, stock, orders, relation managers, status actions, dashboard widgets | | [Blog](/examples/blog/) | Author scoping, editorial workflow, m2m tags, comments | The shop and blog are generated from the `shop` and `blog` starters and kept as examples; the vet clinic is built from a fresh app in its tutorial. All three include: - A seeded SQLite database and demo accounts. - One resource file per model, with policies and action handlers. - A README with the commands and what to try in the UI. ## Run an example ```bash cd examples/vet-clinic # or examples/shop, examples/blog pnpm install pnpm prisma migrate deploy pnpm db:seed pnpm dev ``` The panel is at `/admin`. The demo credentials are listed in each tutorial. ## Create your own ```bash pnpm create dashild@latest my-app --template shop pnpm create dashild@latest my-blog --template blog ``` `--list-templates` shows the bundled starters. ## Why they are outside the workspace An example inside the monorepo would resolve `workspace:*` packages and hide the failures that matter in a real install: missing exports, client components inside `node_modules`, Tailwind not scanning the package build, or an alias that only exists in the workspace. These apps install the published packages, so they test what users get. --- # Shop (inventory and orders) Source: https://dashild.vercel.app/examples/shop/ This tutorial builds [examples/shop](https://github.com/dashild/dashild/tree/main/examples/shop): a small shop admin with products, stock, suppliers, customers, orders, and order items. The `shop` starter writes the schema, resources, policies, actions, and seed; this guide explains every piece and shows the running app. 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 `Decimal`, money formatting, relation selects, and filters work. - How declared actions, confirmation, and action handlers fit together. - How relation managers are derived from the schema. - How Stripe links and CSV import/export are wired without API keys. The finished app is in the repository if you want to compare. ## 1. Create the app ```bash pnpm create dashild@latest my-shop --template shop --database sqlite --yes cd my-shop ``` The scaffolder creates a Next.js app, installs Dashild, and applies the `shop` starter. The starter adds: - Six models: `Category`, `Supplier`, `Product`, `Customer`, `Order`, and `OrderItem`. - One resource file per model under `src/dashild/resources/`. - `src/dashild/policies.ts`, `src/dashild/actions/index.ts`, and the panel registration in `src/dashild/panel.ts`. - A seed with demo products, customers, and orders. - The Stripe and CSV glue, already wired into the route. `--database sqlite` keeps the example self-contained: the database is a file (`prisma/dev.db`), so you do not need a server. The shop starter is staff-only: it writes `ALLOW_SIGNUP="false"`, `REQUIRE_EMAIL_VERIFICATION="true"`, and a `DASHILD_STAFF_EMAILS` allowlist with the seeded staff. Update that list when you add staff; an account outside it cannot read or write the shop even if signup is enabled later. `BETTER_AUTH_URL` must match the URL you open in the browser. The scaffold sets `http://localhost:3000`. If you change the port, set it before `pnpm dev`: ```bash BETTER_AUTH_URL=http://localhost:3001 pnpm dev ``` The starter is a **folder template**: a short `template.json` plus real files under `packages/create-dashild/templates/shop`. List what is available with: ```bash pnpm create dashild@latest --list-templates ``` ![Sign in to the shop panel](/images/examples/shop/login.png) *The seeded demo account signs in at `/login`; the panel lives at `/admin`.* ## 2. The data model `prisma/schema.prisma` describes the tables. Prisma generates a typed client; Dashild reads the metadata to know which fields each model has. The shop models are a small catalog plus orders: ```prisma title="prisma/schema.prisma" enum OrderStatus { PENDING PAID SHIPPED CANCELLED } model Product { id String @id @default(uuid()) name String sku String @unique description String? price Decimal stock Int @default(0) categoryId String? category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull) supplierId String? supplier Supplier? @relation(fields: [supplierId], references: [id], onDelete: SetNull) orderItems OrderItem[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } model Order { id String @id @default(uuid()) number String @unique customerId String customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict) status OrderStatus @default(PENDING) total Decimal @default(0) items OrderItem[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } ``` A few details matter for the admin: - **`Decimal`** is money. Prisma sends and receives it as a string; Dashild keeps it as a string on the wire and only converts it for display. - **`@unique`** on `sku` and `Order.number` becomes a server validation error, not a client-side guess. - **Optional relations** (`categoryId`, `supplierId`) can be cleared. Required relations (`Order.customer`, `OrderItem.order`) cannot. - **`@@unique([orderId, productId])`** on `OrderItem` stops the same product from appearing twice in one order. ## 3. Create the database and seed it ```bash pnpm prisma migrate dev --name init pnpm prisma generate pnpm db:seed ``` - `migrate dev` writes and applies the migration. - `prisma generate` regenerates the Prisma client **and** the Dashild metadata. On Prisma 7, `migrate dev` does not run this step for the metadata; skipping it leaves `make:resource` and the panel looking at the old models. - `db:seed` creates the demo users through Better Auth and inserts products, customers, orders, and items. The account is: | Email | Password | | --- | --- | | `ana@shop.test` | `dashild123` | | `bruno@shop.test` | `dashild123` | `pnpm db:seed` is re-runnable: it deletes the demo rows in dependency order and creates them again. ## 4. The panel, its resources, and its widgets `src/dashild/panel.ts` is the only place that decides what appears in the panel: ```ts title="src/dashild/panel.ts" export const panel = definePanel({ title: "Admin", path: "/admin", locale: "en", resources: [ categoryResource, customerResource, orderItemResource, orderResource, productResource, supplierResource, ], auth: { getCurrentUser, signOut }, }); ``` A resource is **data**, not a page. The catch-all route `src/app/admin/[[...dashild]]/page.tsx` resolves every list, form, detail, and relation manager from this array. There is no generated page per model. ![The shop dashboard with widgets](/images/examples/shop/dashboard.png) *The dashboard combines stats, a chart, a table and the resource cards. Each widget is one file; the cards still open the same catch-all route with a different slug.* The example registers three widgets in the same panel: ```ts title="src/dashild/panel.ts" widgets: [ revenueOverviewWidget, ordersChartWidget, latestOrdersWidget, ], ``` - `revenue-overview.ts` returns four **stats** (revenue, orders, customers, low stock). - `orders-chart.ts` returns a **doughnut chart** with orders per status. - `latest-orders.ts` returns a **table** with the five newest orders. All three receive the scoped Prisma client, so their numbers follow the same policies as the tables. The [widgets guide](/guides/widgets/) explains the API, the chart types, and how to write your own. The starter groups them in the sidebar: - **Catalog**: Categories, Products, Suppliers. - **Sales**: Customers, Order items, Orders. The group comes from `navigation.group` in each resource file. ## 5. Products: money, stock, filters, and relations Open `src/dashild/resources/product.ts`. The column list is the table; the field list is the form: ```ts title="src/dashild/resources/product.ts" export const productResource = defineResource({ model: "Product", navigation: { label: "Products", slug: "products", group: "Catalog", icon: "package", }, table: { searchable: ["name", "sku"], pageSize: 25, columns: [ { field: "name", sortable: true }, { field: "sku", sortable: true }, { field: "price", format: "currency", currency: "EUR", sortable: true }, { field: "stock", format: "number", sortable: true }, { field: "category", display: "name", sortable: true }, { field: "supplier", display: "name" }, ], filters: [ { field: "category", type: "relation", label: "Category", display: "name" }, { field: "supplier", type: "relation", label: "Supplier", display: "name" }, ], }, form: { fields: [ { field: "name", type: "text", rules: { required: true } }, { field: "sku", type: "text", rules: { required: true } }, { field: "description", type: "textarea" }, { field: "price", type: "number", rules: { required: true } }, { field: "stock", type: "number", default: 0 }, { field: "category", type: "relation", relation: "category", display: "name" }, { field: "supplier", type: "relation", relation: "supplier", display: "name" }, ], }, policy: { scope: "public" }, }); ``` ![The products table](/images/examples/shop/products.png) *`price` is rendered as EUR, `stock` as a number, and the relation columns show the display field instead of a raw id.* ![Creating a product](/images/examples/shop/product-create.png) *The create form uses the same field list with empty values.* ![Editing a product](/images/examples/shop/product-edit.png) *The same field definitions build the create and edit forms. `Decimal` values arrive as strings; `format: "currency"` handles the display.* Two rules avoid surprises: - `format: "currency"` is presentation only. Validation and storage still use the Prisma `Decimal`; do not do arithmetic on the formatted value. - The `policy.scope` string is a marker, not a rule. `"public"` selects nothing; the real predicate lives in `policies.ts` (step 9). Filters are server-side. The options for a relation filter are loaded with the active user's policy scope, so a filter cannot reveal rows the user cannot read. Combining filters is a normal GET form, which means the URL is shareable and the back button works. ![Products filtered by category](/images/examples/shop/products-filtered.png) *Filtering by Category is a GET request: the URL, pagination, and sorting stay in sync.* ## 6. Actions: restock and order status Declaring `table.actions` replaces the built-in create/view/edit/delete list, so the resource lists them explicitly and then adds its own: ```ts title="src/dashild/resources/product.ts" actions: [ { name: "create", placement: "header" }, { name: "view", placement: "row" }, { name: "edit", placement: "row" }, { name: "delete", placement: "row" }, { name: "restock", label: "Restock +10", placement: "row", requires: "restock", variant: "secondary", data: { amount: 10 }, }, ], ``` `requires` is the policy predicate that decides whether the action is visible and allowed. `data` is passed to the handler; `confirm: true` asks before running. ![Product row actions](/images/examples/shop/product-actions.png) *The row menu contains the declared actions. “Restock +10” sends `{ amount: 10 }` to the handler.* The handler lives in `src/dashild/actions/index.ts` and runs on the server: ```ts title="src/dashild/actions/index.ts" Product: { restock: async (context) => { if (!context.id) return { ok: false, message: "Missing product id." }; const db = dbFrom(context); if (!db) return { ok: false, message: "Database client unavailable." }; const amount = Number(context.data?.amount ?? 10); await db.product.update({ where: { id: context.id }, data: { stock: { increment: Number.isFinite(amount) ? amount : 10 } }, }); return { ok: true, message: `Stock increased by ${amount}.` }; }, }, ``` `context.db` is Prisma extended with the policy scope. It is typed `unknown` and can be `undefined`, so the example narrows it with `dbFrom`. An update on a row outside the scope fails even with a guessed id. `context.id` is optional: always check it before a row action. Orders use the same pattern to change status: ```ts title="src/dashild/resources/order.ts" actions: [ // create, view, edit, delete... { name: "markPaid", label: "Mark paid", placement: "row", requires: "markPaid", variant: "secondary" }, { name: "ship", label: "Ship", placement: "row", requires: "ship", variant: "secondary" }, { name: "cancelOrder", label: "Cancel", placement: "row", requires: "cancelOrder", confirm: true }, ], ``` Do not name a custom action `cancel`: it is a built-in form action and the panel would ignore yours. The example uses `cancelOrder`. ![The orders table](/images/examples/shop/orders.png) *Status is a badge with a tone per enum value; the actions change it without a page reload.* ## 7. Orders and the relation manager Open an order from **Orders → row menu → View**. The detail page shows the record and, below it, every one-to-many or many-to-many relation that has a registered child resource. ![An order with its items](/images/examples/shop/order-detail.png) *The order detail includes the `Order items` relation manager automatically.* ![The relation manager close up](/images/examples/shop/order-relation-manager.png) *Rows can be edited or deleted, and “Create related” opens the child form with the parent id already set.* ![Creating an order](/images/examples/shop/order-create.png) *A normal resource form: the customer relation is a select, and the status is an enum. The order items are managed from the detail page.* The manager is derived, not hand-written: 1. Dashild reads the metadata and finds list fields on `Order` (`items`). 2. It looks for a resource whose `model` matches the child (`OrderItem`). 3. It checks the child policy allows `list`. 4. It loads the rows with the child's scope and the parent id applied. The child's foreign key decides what is possible. `OrderItem.orderId` is required, so an item cannot be dissociated from its order; it can only be edited or deleted. If the foreign key is optional, the manager also offers “associate” and “dissociate”. Many-to-many relations (the blog's `tags`) use attach/detach. The **Order items** resource also exists as a top-level list, so you can inspect all items and filter them by order or product: ![Order items table](/images/examples/shop/order-items.png) *Relations are visible from both sides: the parent detail and the child list.* ## 8. Customers and Stripe links Customers store the id the app already synced from Stripe: ```prisma model Customer { id String @id @default(uuid()) name String email String? phone String? stripeCustomerId String? orders Order[] } ``` ![The customers table](/images/examples/shop/customers.png) *The customer list stores the Stripe id on the record; the action below reads it when you open the dashboard.* The resource declares an action with no custom handler: ```ts title="src/dashild/resources/customer.ts" actions: [ // create, view, edit, delete... { name: "openInStripe", label: "Open in Stripe", placement: "row", variant: "outline", }, ], ``` The handler is the shared `stripeActionHandler`: ```ts title="src/dashild/actions/index.ts" Customer: { openInStripe: stripeActionHandler({ type: "customer", field: "stripeCustomerId", mode: "test", }), }, ``` ![Customer row actions with the Stripe link](/images/examples/shop/customer-stripe-action.png) *“Open in Stripe” reads the id through the scoped client and returns a dashboard URL.* What this does **not** do: call the Stripe API, read an API key, or receive webhooks. It builds `https://dashboard.stripe.com/test/customers/` and opens it. Use `mode: "live"` for live ids. The same helper supports subscriptions, invoices, payments, products, and prices. ## 9. Policies `src/dashild/policies.ts` is the authority. The shop is staff-only: public signup is closed and `DASHILD_STAFF_EMAILS` is an allowlist. A signed-in account outside the list sees nothing: ```ts title="src/dashild/policies.ts" const staff = (ctx: { user: { email?: string } }) => { const allowed = (process.env.DASHILD_STAFF_EMAILS ?? "") .split(",") .map((email) => email.trim().toLowerCase()) .filter(Boolean); const email = ctx.user.email?.toLowerCase(); return Boolean(email && allowed.includes(email)); }; const scope = (ctx: { user: { email?: string } }) => staff(ctx) ? {} : null; Product: { scope, can: { create: staff, update: staff, delete: staff, restock: staff, }, }, ``` `scope` returns a Prisma `where`. `{}` means “all rows”; `null` denies the resource. `can` decides permissions and declared actions are deny-by-default: if `restock` is missing from the predicates, the action is hidden and the server refuses it. The seed enables signup only inside its own process so Better Auth can create the demo staff; the running app keeps `ALLOW_SIGNUP="false"`. When you add staff, update `DASHILD_STAFF_EMAILS`. If you need roles instead of an allowlist, read `User.role` in the session and replace `staff` with `hasRole(ctx, "ADMIN")`; the [multi-tenancy guide](/guides/multi-tenancy/) shows the same pattern with organizations. ## 10. CSV import and export Every list has **Export** and **Import** buttons. **Export** uses the current view: search, filters, sort, and page size. It writes the visible columns except `Bytes` fields, and relations become ids. ![CSV import result](/images/examples/shop/import-result.png) *Import reports how many rows succeeded and how many failed. It creates rows; it does not update existing ones.* ![The imported product](/images/examples/shop/imported-row.png) *The new row is a normal product: policy, validation, and the table refresh all apply.* Rules worth knowing: - **Export cap**: 5,000 rows. The response reports `truncated` when the view is larger. - **Import cap**: 1,000 rows and 2 MB. - **Headers** must match `form.fields` (`name`, `sku`, `price`, ...). Unknown columns are ignored. - **Relations** use the form field name (`category`), with the id as the value, not the display name. - **Types**: `Int`/`Float` are coerced, booleans accept `true`/`1`, and `Decimal`/`BigInt` stay strings. - **Create only**: the import calls the same server save path as the form, so validation, uniqueness, and policies apply. It is not an upsert. Advanced import mapping, updates, and background jobs are reserved for Dashild Pro; the open CSV path is deliberately small. ## 11. Run it and try ```bash pnpm dev ``` Open [http://localhost:3000/admin](http://localhost:3000/admin) and sign in as `ana@shop.test` / `dashild123`. What to check: 1. **Products**: filter by category, sort by price, and open a product. Change the stock and save; the table refreshes. 2. **Restock +10**: run it from a row menu and watch stock increase. 3. **Orders**: filter by status, then open one. Add an item with **Create related**, edit its quantity, and delete it. 4. **Order actions**: “Mark paid”, “Ship”, and “Cancel”. Cancel asks for confirmation. 5. **Customers**: open “Open in Stripe” (test mode) with a seeded `stripeCustomerId`. 6. **CSV**: export products, change a price in the file, and import it as a new row with a new `sku`. 7. **dark mode**: the theme toggle is in the header. Finally, verify the app the same way CI does: ```bash pnpm dashild doctor pnpm build ``` ## 12. Add a dashboard widget The dashboard is built from widgets, and each widget is one file. Create one with the command and a type: ```bash pnpm dashild make:widget LowStock --stats pnpm dashild make:widget RevenueChart --chart bar pnpm dashild make:widget LatestCustomers --table ``` `make:widget` writes `src/dashild/widgets/.ts` and registers the export in `panel.ts`. The file is write-once. A stats widget returns cards: ```ts title="src/dashild/widgets/low-stock.ts" export const lowStockWidget = defineWidget({ type: "stats", title: "Low stock", width: "full", async data({ db }) { const client = db as ScopedClient; const count = await client.product.count({ where: { stock: { lt: 10 } } }); return [ { label: "Products", value: count, description: "Under 10 units", color: count > 0 ? "warning" : "success", }, ]; }, }); ``` A chart returns labels and datasets, and a table returns columns plus rows. The full contract, including `width`, `sort`, `canView` and the chart types, is in the [widgets guide](/guides/widgets/). ## 13. Extend it The starter is a normal Dashild app. To add a model: ```bash pnpm prisma migrate dev --name add_reviews pnpm prisma generate pnpm dashild make:resource Review ``` `make:resource` writes `src/dashild/resources/review.ts`, registers it in `panel.ts`, and adds a fail-closed policy entry. Edit the columns, fields, and predicates, then run `pnpm dashild doctor` and `pnpm build`. To add an action: ```bash pnpm dashild make:action Review approve ``` That appends a handler stub without touching the resource. Declare it in `table.actions` or `form.actions`, add the predicate to `policies.ts`, and implement it with the scoped client. For a deeper walkthrough of generating each resource by hand, read the [vet clinic tutorial](/examples/vet-clinic/). It covers `make:resource`, custom cells, tenancy, and role-aware actions from an empty app. ## Troubleshooting - **`make:resource` says the model does not exist**: the metadata is stale. Run `pnpm prisma generate` after `migrate dev`. - **Empty relation options**: the child resource is missing from `panel.ts`, or its policy denies `list`. - **“No Stripe id”**: the customer has no `stripeCustomerId`; the helper does not look the customer up in Stripe. - **CSV import skips a column**: the header must match a form field exactly. Relations need ids, not names. - **A custom action does not appear**: the name collides with a built-in (`cancel`, `delete`, `save`...) or the policy predicate is missing. --- # Vet clinic (multi-tenant) Source: https://dashild.vercel.app/examples/vet-clinic/ This tutorial builds [examples/vet-clinic](https://github.com/dashild/dashild/tree/main/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](/reference/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. ## 1. Create the app ```bash 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. ## 2. Model the clinic `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 title="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 title="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. ## 3. Create the database and seed it `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. ```bash 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. ```ts title="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: ```json title="package.json" { "scripts": { "db:seed": "tsx prisma/seed.ts" } } ``` ```bash 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. ## 4. Generate the first resource (Owners) 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. ```bash 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: ```ts title="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](/images/examples/vet/owners.png) *The first resource in the panel: search, sorting, pagination, and the create button all come from the definition above.* ## 5. Generate the other resources The rest follow the same command. Run them now: ```bash 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. :::note `make:resource User` writes `user.ts`. The example renames it to `staff.ts` because it only edits staff (name and role), and updates the import in `panel.ts`. Renaming a file is fine as long as the panel imports the new path. ::: ![Creating an owner](/images/examples/vet/owner-create.png) *The form is built from `form.fields`; the server performs the final validation.* ## 6. Pets and a custom cell 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: ```bash 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: ```tsx title="src/components/dashild/species-cell.tsx" "use client"; import type { CellRendererProps } from "@dashild/admin"; const SPECIES: Record = { 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 ( {species.label} ); } ``` Then register it. Registration happens on the client, because components are functions and cannot travel from a server component as props: ```tsx title="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 ( {children} ); } ``` Finally, use `cell: "species"` in the pet resource and include a photo field: ```ts title="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](/images/examples/vet/pets.png) *The `species` column renders the registered cell: an emoji and a readable label instead of the raw `DOG`/`CAT` value.* ![Creating a pet](/images/examples/vet/pet-create.png) *The species and owner fields are selects; the photo field is a file picker.* ![Editing a pet with the photo field](/images/examples/vet/pet-edit.png) *`{ field: "photo", type: "bytes" }` renders a file picker; the file travels as base64 and is stored in `Bytes`.* ## 7. Appointments, filters, and actions The appointment resource adds filters and actions: ```ts title="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](/images/examples/vet/appointments.png) *Status, pet, and vet filters are resolved on the server and scoped to the active clinic.* ![Appointment row actions](/images/examples/vet/appointment-actions.png) *The declared actions appear in the row menu. The policy decides which roles see “Mark attended” and “Cancel”.* ## 8. Policies and roles `make:resource` added a fail-closed entry for every model. Replace `policies.ts` with the real rules: ```ts title="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({ 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](/images/examples/vet/staff.png) *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. ## 9. Action handlers The resource declares the action; the handler runs on the server: ```ts title="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; }; } async function setStatus( context: Parameters>[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> > = { 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. ## 10. A custom icon 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: ```bash pnpm add lucide-react ``` ```tsx title="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 = { shield: Shield, }; export function AppIconProvider({ children }: { children: React.ReactNode }) { return {children}; } ``` ## 11. Run it and try the roles ```bash pnpm dev ``` Open [http://localhost:3000/admin](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](/images/examples/vet/dashboard.png) *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](/images/examples/vet/tenant-switcher.png) *Ana belongs to both clinics. The switcher is validated on the server; the cookie alone cannot grant access to another tenant.* ![The Beta dashboard](/images/examples/vet/tenant-beta-dashboard.png) *The header, lists, and form options now use Clínica Beta. Switching back to Acme restores its data.* ![Beta only shows its own data](/images/examples/vet/tenant-beta-owners.png) *After switching, the owners list contains only Hugo Santos. The same policy scope applies to lists, form options, and relation managers.* ![Beta pets](/images/examples/vet/tenant-beta-pets.png) *The pets list follows the active clinic too: Beta only has Toby.* ## 12. Finish the example The remaining resources are generated and edited the same way. Copy them from the repository: - [visit.ts](https://github.com/dashild/dashild/blob/main/examples/vet-clinic/src/dashild/resources/visit.ts) - [vaccination.ts](https://github.com/dashild/dashild/blob/main/examples/vet-clinic/src/dashild/resources/vaccination.ts) - [staff.ts](https://github.com/dashild/dashild/blob/main/examples/vet-clinic/src/dashild/resources/staff.ts) - [seed.ts](https://github.com/dashild/dashild/blob/main/examples/vet-clinic/prisma/seed.ts) ## Troubleshooting - **`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. --- # AI assistant Source: https://dashild.vercel.app/getting-started/ai/ Dashild ships a **skill** for coding agents (Claude Code, OpenCode, Cursor, and anything that reads `AGENTS.md`). It teaches the agent the framework's rules, the file layout, and how to verify its own work, so it can build a tailored dashboard instead of guessing the API. ## Install ```bash pnpm dashild skill install ``` It copies the skill into the project's agent folders and adds a pointer to `AGENTS.md`: ```text .claude/skills/dashild/SKILL.md .claude/skills/dashild/references/*.md .opencode/skills/dashild/SKILL.md .opencode/skills/dashild/references/*.md AGENTS.md (a short Dashild block) ``` Choose one agent with `--agent claude` or `--agent opencode`. Reinstalling replaces the skill and refreshes the block; it does not duplicate it. ## What the skill knows - A resource is data; there is one route and no page generator. - `make:resource` writes a resource and a fail-closed policy entry. - `type: "select"` for form enums; `type: "enum"` only for filters. - Built-in action names (`create`, `view`, `edit`, `delete`, `save`, `cancel`) cannot be reused for custom actions. - Scope semantics: tenant, author, public; `null` denies; creates are not scoped. - Relations, filters, custom cells, and `ui:add`. - Verification: `dashild doctor` and `pnpm build` are mandatory. The skill links to four references (resources, policies, actions, verification) so the agent loads detail only when it needs it. ## Ask it for a dashboard ```text Build a Dashild admin for a small clinic: owners, pets, appointments and visits. Reception manages owners and appointments, vets write visits, and an admin manages staff. Single clinic for now. ``` The agent should propose the Prisma schema, generate the resources, write the policies and actions, seed the database, and run `dashild doctor` plus the build. Review the diff; the skill is a guide, not a substitute for review. ## Machine-readable docs - [dashild.vercel.app/llms.txt](https://dashild.vercel.app/llms.txt): a short index for assistants. - [dashild.vercel.app/llms-full.txt](https://dashild.vercel.app/llms-full.txt): the English docs in one file. ## Manual install If your agent uses another folder, copy `packages/cli/skills/dashild` from the [repository](https://github.com/dashild/dashild/tree/main/packages/cli/skills/dashild) and point the agent at `SKILL.md`. ## Version The skill is tied to the CLI that installs it. After upgrading Dashild, run `pnpm dashild skill install` again so the skill matches the new version. --- # Installation Source: https://dashild.vercel.app/getting-started/installation/ Dashild is an admin layer for Next.js + Prisma. A resource is a data file; there are no pages to generate or files to keep in sync. ## Requirements - Node.js 22 or newer. - Next.js 15 or 16 with the App Router. - Prisma 7.10 or newer and a client generated with the `prisma-client` provider. - PostgreSQL, MySQL, or SQLite. PostgreSQL, SQLite, and MySQL 8.4 run end-to-end in CI; MariaDB uses the same adapter as MySQL but is not in the CI matrix. - Tailwind CSS v4 and shadcn/ui for the shell. These are documented ranges, not runtime checks: the CLI does not verify the Next.js or Prisma version of your project. ## Create a new app ```bash pnpm create dashild@latest my-app ``` The scaffolder runs `create-next-app` non-interactively (`--yes --empty`) and then asks its own questions: starter, auth, database, and whether to install, migrate, and seed. It also works with flags: `pnpm create` downloads and runs the project generator without installing it as a permanent dependency in your current project. `my-app` is the new directory name. The example below selects a starter and PostgreSQL, supplies the database URL, chooses pnpm, and accepts defaults so the command can run without prompts. ```bash npx create-dashild@latest my-app \ --template demo \ --database postgresql \ --database-url "$DATABASE_URL" \ --pm pnpm \ --yes ``` | Flag | Values | | --- | --- | | `--template` | `basic`, `demo`, `local:`, `github:/#` | | `--auth` | `better-auth`, `none` | | `--database` | `postgresql`, `mysql`, `sqlite` | | `--database-url` | Connection string | | `--direct-url` | Non-pooled URL for migrations | | `--pm` | `pnpm`, `npm`, `yarn`, `bun` | | `--name` | Project name when you omit the positional argument | | `--dir` | Target directory (defaults to the project name) | | `--path` | Panel route (defaults to `/admin`) | | `--locale` | `en` or `es`, for prompts and generated labels | | `--tenancy` | Organizations, tenant session, and switcher (Better Auth) | | `--no-install` | Skip dependency installation | | `--no-git` | Skip `git init` | | `--no-migrate` | Do not apply the schema | | `--no-seed` | Do not load starter data | | `-y`, `--yes` | Accept the defaults without prompting | | `--dry-run` | Print the plan without writing | | `--list-templates` | List bundled starters | `--dry-run` still resolves a `github:` starter, which means downloading and caching it in `~/.cache/dashild/templates`. If the database is unreachable, the app is still created and the migration and seed commands are printed as pending steps. See [Templates](/reference/templates/) for the starter format. ## Manual installation ```bash pnpm add @dashild/core@alpha @dashild/admin@alpha @dashild/prisma@alpha pnpm add -D @dashild/cli@alpha ``` Add the two Prisma generators: ```prisma generator client { provider = "prisma-client" output = "../src/generated/prisma" } generator dashild { provider = "dashild-prisma-generator" output = "../src/generated/dashild" } ``` The `dashild` generator writes `dashild-metadata.json`, the contract used by the CLI, the runtime, and the panel. The CLI and the panel only read it. Prisma 7 reads the connection from `prisma.config.ts`: ```ts import "dotenv/config"; import { defineConfig, env } from "prisma/config"; export default defineConfig({ schema: "prisma/schema.prisma", datasource: { // DIRECT_URL wins when set: use it for migrations behind a pooler. url: process.env.DIRECT_URL || env("DATABASE_URL"), }, }); ``` The app also needs a Prisma client with a driver adapter: ```ts import { PrismaPg } from "@prisma/adapter-pg"; import { PrismaClient } from "@/src/generated/prisma/client"; export const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }), }); ``` For SQLite use `@prisma/adapter-better-sqlite3` and `better-sqlite3`; for MySQL/MariaDB, `@prisma/adapter-mariadb`. The scaffolder picks the right one. ### Database Dashild does not start a database. Point `DATABASE_URL` at a running instance: ```bash # SQLite DATABASE_URL="file:./prisma/dev.db" # PostgreSQL DATABASE_URL="postgresql://user:password@host:5432/database" # MySQL DATABASE_URL="mysql://user:password@host:3306/database" ``` For SQLite, the generated `prisma.config.ts` and the adapter resolve the path from the project root, and the scaffolder verifies the file exists after migrating. The scaffolder installs `better-sqlite3` with the Node that runs the app (pinning `PATH` and `npm_config_target`) because pnpm does not ship `node-gyp`. ## Mount the panel `dashild init` reads `dashild-metadata.json`, so generate the Prisma client and the metadata first. `prisma generate` runs both configured Prisma generators: the client generator makes the typed database API, and the Dashild generator makes metadata used to build the admin UI. ```bash pnpm prisma generate pnpm dashild init --auth better-auth ``` `dashild init` plans the panel files and auth integration. It prints the plan first; without `--yes` it does not apply it. Review that plan before accepting it: ```bash pnpm dashild init --auth better-auth --yes ``` If the metadata is not in one of the standard paths, pass it explicitly with `--metadata prisma/generated/dashild/dashild-metadata.json`. It writes: ```text src/dashild/panel.ts src/dashild/policies.ts src/dashild/actions/index.ts src/dashild/icons.tsx src/dashild/runtime.ts src/dashild/server.ts src/dashild/registry.tsx src/app//[[...dashild]]/page.tsx ``` With `--auth better-auth` it also writes login, signup, session, password reset, and API route files, and appends the Better Auth models to the schema. See [Authentication](/guides/authentication/). Then regenerate because `init --auth better-auth` may have changed the Prisma schema. `db push` synchronizes that schema with the configured database without creating a versioned migration. For a team or production workflow, use Prisma migrations instead: ```bash pnpm prisma generate pnpm prisma db push ``` `init` appends missing keys to `.env.example`; it never writes `.env`. If `app/admin/page.tsx` already exists, `init` proposes `/panel`, `/admin-panel`, or `/dashild`. Use `--path /other-route` to force one. `--force` overwrites the generated files (including the auth ones) but does not bypass a route conflict caused by an explicit `--path`; pick another route instead. ## Tailwind The shell lives in `@dashild/admin`; Tailwind must scan its build. Add this to your global CSS (adjust the relative path): ```css @source "../../node_modules/@dashild/admin/dist"; ``` You also need the shadcn theme variables (`--background`, `--foreground`, `--primary`, `--sidebar`, etc.). The scaffolder writes a complete `globals.css`; for a manual install, start from `apps/playground/app/globals.css` in the repository. Define a real font stack in `--font-sans`; a self-referencing variable leaves the app in Times New Roman. ## First resource ```bash pnpm dashild make:resource Customer pnpm dashild doctor ``` The first command takes a Prisma model name and creates a resource definition: the panel's instructions for displaying and editing that model. It registers the new file in `panel.ts` and adds a fail-closed policy entry. It never overwrites an existing resource file. The second command checks that resources, metadata, policies, and action handlers are wired consistently; it does not repair problems automatically. The policy entry starts as `scope: () => null`, so the resource returns 404 until you define its scope and permissions. See [Policies and security](/guides/policies/) and [Resources](/guides/resources/). ## Run ```bash pnpm dev ``` `pnpm dev` runs the development server defined by your app's `package.json`. The panel is at `http://localhost:3000/admin` (or the route you chose). In development use `localhost`, not `127.0.0.1`: Next 16 blocks assets and hydration from unlisted origins. The scaffold adds `allowedDevOrigins: ["127.0.0.1", "localhost"]`; add any other domain you use. ## Next steps - [Resources](/guides/resources/): tables, forms, filters, and actions. - [Policies and security](/guides/policies/): scoping and roles. - [Authentication](/guides/authentication/): Better Auth, email, and resets. - [CLI](/reference/cli/): every command. --- # Upgrading Source: https://dashild.vercel.app/getting-started/upgrading/ Apps generated by `create-dashild` and `dashild init` pin the exact version of the four packages, so nothing changes until you ask: ```json title="package.json" "@dashild/core": "0.1.0-alpha.11", "@dashild/admin": "0.1.0-alpha.11", "@dashild/prisma": "0.1.0-alpha.11", "@dashild/cli": "0.1.0-alpha.11" ``` ## Check for updates ```bash pnpm dashild upgrade --check ``` It prints the current and target versions and exits with code 1 when the app is behind. Use it in CI if you want to be told when a new release exists. ```bash pnpm dashild upgrade --dry-run ``` `--dry-run` shows the plan without writing or installing. ## Upgrade ```bash pnpm dashild upgrade ``` It: 1. Resolves the target version from the npm `latest` tag (the four packages must match; otherwise it stops). 2. Rewrites the four versions in `package.json`. 3. Records the version in `dashild.json` (`stackVersion`). 4. Runs the project's package manager (`pnpm`, `npm`, `yarn`, or `bun`). 5. Runs `prisma generate`, so the client and the Dashild metadata match the new packages. Options: | Flag | Effect | | --- | --- | | `--tag alpha` | Use the `alpha` dist-tag instead of `latest`. | | `--to ` | Install an exact version. | | `--no-install` | Skip the package manager step. | | `--no-generate` | Skip `prisma generate`. | | `--cwd ` | Project root (defaults to the current directory). | ## The generated glue is yours `dashild init` writes `panel.ts`, `policies.ts`, `runtime.ts`, the route, and the auth helpers once. `upgrade` never rewrites them: they are app code, and a framework that silently replaces them is worse than one that asks. New files carry a marker with the CLI that created them: ```ts title="src/dashild/panel.ts" // dashild:generated 0.1.0-alpha.11 import { definePanel } from "@dashild/core"; ``` After an upgrade, the command lists the glue it found and the version in each marker. Files without a marker were generated before markers existed: review them by hand against the current docs. Common changes between releases: - A route may need a new prop (`themeAction`, `organizations`, ...). - A generated session may need tenant fields. - The panel may need `brand` or a new resource entry. If a release changes the glue, the changelog says which file and what to add, and the command points at the Upgrading guide. ## What can break | Area | Why it can break | | --- | --- | | `@dashild/core` types | Public API changes (`defineResource`, `definePanel`, `CurrentUser`). | | Metadata | The generator and the runtime share `formatVersion`; always run `prisma generate`. | | Generated glue | New features may require a manual prop or file. | | `@dashild/admin` imports | `@dashild/admin/ui/*` and the Tailwind `@source` path. | | Database | Only if the release adds a feature you enable (tenancy adds fields). | ## Alpha policy While Dashild is alpha, every release documents breaking changes in the [changelog](https://github.com/dashild/dashild/blob/main/CHANGELOG.md) and the version keeps the `0.1.0-alpha.N` format, so the number alone does not tell you whether an update is safe. Read the entry and run your tests. From 1.0, semantic versioning applies: breaking changes are major releases with a migration guide. --- # Authentication Source: https://dashild.vercel.app/guides/authentication/ Dashild does not ship an auth library. The panel needs two things from the app: ```ts export const panel = definePanel({ // ... auth: { getCurrentUser, signOut, // optional }, }); ``` `getCurrentUser` runs on the server and returns the signed-in user or `null`. `signOut` is optional; when present, the user menu shows a sign-out action. ## Better Auth ```bash pnpm dashild init --auth better-auth --yes ``` `init` creates the generated auth files and connects the app to Better Auth. `--auth better-auth` selects that integration; `--yes` applies the plan without asking for confirmation. Review the generated files and environment variables before using the app. This writes: ```text src/lib/auth.ts src/lib/auth-client.ts src/lib/session.ts src/lib/auth-actions.ts src/lib/email.ts src/app/api/auth/[...all]/route.ts src/app/login/page.tsx src/app/signup/page.tsx src/app/forgot-password/page.tsx src/app/reset-password/page.tsx src/components/dashild/login-form.tsx src/components/dashild/signup-form.tsx src/components/dashild/forgot-password-form.tsx src/components/dashild/reset-password-form.tsx ``` The folders are conditional: if the app already has `lib/` and `components/` at the root instead of under `src/`, the files go there. The `app` directory follows the same rule. It also adds `better-auth` to `package.json`. ### Prisma models If the schema has none of `User`, `Session`, `Account`, or `Verification`, `init` appends all four. If it finds **any** of them, it adds none and warns; adapt the existing models yourself. The check is all-or-nothing. ## Environment `create-dashild` writes `.env` and a committed `.env.example`. `dashild init` only appends missing keys to `.env.example`; it never writes `.env`. | Variable | Where | Purpose | | --- | --- | --- | | `DATABASE_URL` | `.env` and `.env.example` | App and Prisma connection. | | `DIRECT_URL` | `.env` when given; commented placeholder in `.env.example` | Non-pooled URL for migrations. | | `BETTER_AUTH_SECRET` | With Better Auth | Session signing. Generate with `openssl rand -base64 32`. | | `BETTER_AUTH_URL` | With Better Auth | Public origin; must match the browser URL. | | `ALLOW_SIGNUP` | With Better Auth | `false` closes public sign-up. | | `REQUIRE_EMAIL_VERIFICATION` | With Better Auth | `true` requires the verification link. | | `RESEND_API_KEY` | `.env.example` only, commented (Better Auth) | If set, `sendEmail` sends through Resend. | | `EMAIL_FROM` | `.env.example` only, commented (Better Auth) | Resend sender. | The email keys are never written to `.env`: uncomment them there (or add them to your deployment environment) when you configure a provider. `BETTER_AUTH_URL` must match the origin you open in the browser. A mismatch makes sign-in fail with an origin error. ## Sign-up, verification, and reset - `ALLOW_SIGNUP=false` disables the sign-up API and the signup page shows “Sign-up disabled”. Create users from your own admin flow. - `REQUIRE_EMAIL_VERIFICATION=true` sends the verification link on sign-up and blocks sign-in until the email is verified. - `/forgot-password` requests a reset link; `/reset-password?token=...` sets the new password. - Rate limiting is enabled (100 requests per minute) in the generated config. ## Email `src/lib/email.ts` uses Resend when `RESEND_API_KEY` is present: ```ts await fetch("https://api.resend.com/emails", { method: "POST", headers: { Authorization: `Bearer ${process.env.RESEND_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ from: process.env.EMAIL_FROM ?? "Dashild ", to, subject, text, }), }); ``` Without a key it logs the email in development and throws in production, so password reset and verification never lose emails silently. Replace it with Postmark, SES, or your own transport if you prefer. ## Your own auth Use the default mode and fill the adapter: ```bash pnpm dashild init --auth none --yes ``` Here `--auth none` tells Dashild not to generate Better Auth. It still creates the panel integration; you then connect your existing authentication system by implementing `getCurrentUser`. ```ts async function getCurrentUser(): Promise { const session = await myAuth.getSession(); if (!session) return null; return { id: session.user.id, email: session.user.email, name: session.user.name, organizationId: session.user.organizationId, roles: session.user.roles, }; } ``` `CurrentUser` requires `id`; `email`, `name`, `organizationId`, and `roles` are optional. Returning `organizationId` and `roles` is enough for [policies](/guides/policies/). For tenant isolation end to end, see [Multi-tenancy](/guides/multi-tenancy/). If the schema already has any Better Auth model, `init --auth better-auth` does not modify the schema; it warns and leaves the adaptation to you. --- # Customization Source: https://dashild.vercel.app/guides/customization/ The shell lives in `@dashild/admin`; the app owns the panel configuration, auth, and any custom components. ## Panel ```ts // src/dashild/panel.ts import { definePanel } from "@dashild/core"; export const panel = definePanel({ title: "Acme", path: "/admin", locale: "en", brand: { name: "Acme" }, theme: { defaultMode: "dark", toggle: true, primary: "zinc" }, sidebar: { collapsible: "icon" }, maxContentWidth: "xl", resources: [customerResource], auth: { getCurrentUser, signOut }, }); ``` `primary` accepts a shadcn/Tailwind palette (`zinc`, `slate`, `blue`, `emerald`, and so on). `locale` switches built-in labels, server validation messages, and the browser-side messages of the form. `theme.defaultMode` accepts `light`, `dark`, or `system`; `system` follows `prefers-color-scheme` and reacts to changes. `brand.logo` replaces the panel mark in the sidebar. Without a logo, the shell renders the Dashild mark, which inherits the theme's text color. `brand.name` is accepted in panel metadata but is not currently rendered by the generated sign-in pages. `domain` is declared metadata only: Next routes by host, so Dashild does not use it to route requests. ### Theme switch `theme.toggle: true` shows the switch only when the route also passes a `themeAction` server action. The route generated by `dashild init` wires it: it reads the `dashild_theme` cookie for the initial mode and passes `toggleTheme`, which cycles `light` → `dark` → `system` and writes the cookie. On a manual install without that wiring, the switch is hidden. Add an action like the generated one and pass it to `AdminPage`: ```tsx // src/app/admin/[[...dashild]]/page.tsx const store = await cookies(); const cookieTheme = store.get("dashild_theme")?.value; const theme: ThemeMode = cookieTheme === "light" || cookieTheme === "dark" || cookieTheme === "system" ? cookieTheme : panel.theme?.defaultMode ?? DEFAULT_THEME_MODE; ; ``` `DEFAULT_THEME_MODE` is `dark`. With `system`, the server cannot know the user's preference, so the `dark` class is applied on the client after hydration. ## Cells and fields Cells and fields are React components registered on the client: ```tsx // src/dashild/registry.tsx "use client"; import { registerCell, registerField, registeredCells, registeredFields, } from "@dashild/core"; import { RegistryProvider, type Registry } from "@dashild/admin"; import { AvatarCell } from "../../components/dashild/avatar-cell"; import { EmailField } from "../../components/dashild/email-field"; registerCell("avatar", AvatarCell); registerField("email", EmailField); export function AppRegistryProvider({ children, }: { children: React.ReactNode; }) { return ( {children} ); } ``` The casts are required: `registeredCells()` returns the loose renderer type kept in `@dashild/core` so it does not depend on React types. `dashild init` generates this file with the registration calls commented out; edit it to add yours. Wrap `AdminPage` with `AppRegistryProvider` (the generated route does this), then reference the components from a resource: ```ts table: { columns: [{ field: "name", cell: "avatar" }] } form: { fields: [{ field: "email", component: "email" }] } ``` The renderer props are `CellRendererProps` and `FieldRendererProps` from `@dashild/admin`. `dashild ui:add avatar-cell email-field` copies both templates into `components/dashild/` and prints the exact registration call, for example `registerCell("avatar", AvatarCell)`. Options: `--dir`, `--force`, `--dry-run`, `--cwd`. Unknown names are reported and do not change the exit code. ## Tailwind Tailwind must scan the package build: ```css @source "../../node_modules/@dashild/admin/dist"; ``` The theme variables come from shadcn. Define a real font stack in `--font-sans`; the generated `globals.css` does this for you. ## Icons The shell already resolves 19 icon names: `users`, `user`, `building`, `organization`, `file-text`, `settings`, `database`, `folder`, `chart`, `layout-dashboard`, `package`, `shopping-cart`, `tag`, `calendar`, `mail`, `briefcase`, `credit-card`, `truck`, and `layers`. `src/dashild/icons.tsx` mounts an `IconProvider` that adds **your** extra icons; it does not replace the built-in set. For an unknown resource icon the shell always falls back to a generic table icon, and logs a warning only in development. Action icons have no fallback: an unknown name renders no icon. ## Eject If you want to remove the panel glue, run: ```bash pnpm dashild eject --dry-run pnpm dashild eject --yes ``` It removes `panel.ts`, `policies.ts`, `actions/index.ts`, `icons.tsx`, `runtime.ts`, `server.ts`, `registry.tsx`, the mount route, and the `dashild` script. It keeps resources, the auth files, the Prisma generator, and dependencies, and lists them so you can remove them yourself. Some auth files (`email.ts`, the password pages and forms) are kept but are not listed. Without `--yes` it only prints the plan. --- # Import and export Source: https://dashild.vercel.app/guides/import-export/ Every list page has **Export** and **Import** buttons. Export downloads the current view (search, filters, and sorting) as CSV; import creates rows from a CSV that follows the form fields of the resource. The server resolves the policy for both operations: export needs read access, import runs the same validation and `can.create` check as the form. ## Export - Columns are the resource's table columns; a relation column exports the related **id**, not the label. - `Bytes` columns are skipped. - The cap is 5,000 rows. If the view has more, the export is truncated. - JSON and lists are serialized as JSON strings; dates are ISO 8601. - Cells that start with `=`, `@`, a tab, a CR, or a non-numeric `+`/`-` are prefixed with an apostrophe so spreadsheets keep them as text instead of evaluating a formula. ## Import - The first row is the header. Header names must match `form.fields` (unknown columns are ignored); if no column matches, the import fails. - Rows are **created**, never updated. Use the form for edits. - `id`, `createdAt`, and other fields outside the form are ignored. - Numbers and booleans are parsed from their CSV text; `Decimal` and `BigInt` stay strings. - Relations use the form field name (`category`, not `categoryId`) with the related id as the value. Export an existing row to see the expected values. The server re-checks every id against the related resource's policy scope; an id outside it is a field error. - The cap is 1,000 rows and 2 MB. Errors are reported by row number; valid rows are imported even when others fail. ## New and existing apps `dashild init` generates `exportResource` and `importResource` server actions and passes them to the panel. Apps generated before this feature do not show the buttons; add the two actions and the two props to the mount route, or use the upgrade guide. ## Runtime API ```ts const csv = await runtime.exportCsv(resource, { q: "acme" }, user); const result = await runtime.importCsv(resource, csvText, user); ``` `exportCsv(resource, raw, user)` accepts the same query params as the list (`q`, `sort`, `dir`, and filter fields). `importCsv` returns `{ ok, imported, failed, errors }`. Both are server-only and use the scoped client. --- # Multi-tenancy Source: https://dashild.vercel.app/guides/multi-tenancy/ The tenant is part of the security context, not a filter you remember to add. `CurrentUser` carries `organizationId` and `roles`, the policy layer turns them into a Prisma `where`, and every scoped query applies it on the server. ## What the runtime provides - `CurrentUser.organizationId` and `roles` (both optional). - `PolicyContext` with `user`, `organizationId`, and `roles`. - `scope` per resource, applied to list, count, detail, update, delete, and relation managers. - Fail closed: a resource without a policy, without an entry in `policies.ts`, or whose `scope` returns `null` is denied. - `OrganizationSwitcher` in the sidebar for admins. Tenancy is opt-in per resource: the runtime cannot guess which rows belong to a tenant. A resource is isolated when its policy returns a tenant `where`. ## Scaffold a multi-tenant app ```bash pnpm create dashild@latest my-app --template saas ``` The `saas` starter adds organizations, members, and projects, and enables tenancy for you. If you want the same wiring with another starter: ```bash npx create-dashild@latest my-app --tenancy ``` `--tenancy` requires `better-auth` and a schema that does not have the auth models yet (a fresh scaffold). On an existing app: ```bash pnpm dashild init --auth better-auth --tenancy --yes ``` `init` refuses to guess when auth models already exist: add the organization fields yourself and keep the generated `lib/organization.ts` and `dashild/organization-actions.ts`. ### What it writes ```text Organization model + User.organizationId/role in prisma/schema.prisma src/lib/organization.ts # organizations the user sees, active one src/lib/session.ts # org-aware getCurrentUser src/dashild/organization-actions.ts # switchOrganization server action src/app//[[...dashild]]/page.tsx # passes organizations + switchOrganization ``` The active organization is stored in the `dashild_organization` cookie. It is `httpOnly`, validated on every request, and an admin can only switch to an organization that exists; a member stays in their own. ## Scope every resource ```ts import { definePolicies, hasRole, type CurrentUser } from "@dashild/core"; export const policies = definePolicies({ resources: { Project: { scope: (ctx) => ctx.organizationId ? { organizationId: ctx.organizationId } : null, can: { create: (ctx) => hasRole(ctx, "ADMIN", "USER"), update: (ctx) => hasRole(ctx, "ADMIN", "USER"), delete: (ctx) => hasRole(ctx, "ADMIN"), }, }, Organization: { scope: (ctx) => (ctx.organizationId ? { id: ctx.organizationId } : null), can: { create: () => false, update: (ctx) => hasRole(ctx, "ADMIN"), delete: () => false, }, }, }, }); ``` Returning `null` denies the resource for a session without an organization, which is what you want before the first request resolves one. `create` is not constrained by a read scope: a scoped resource cannot create unless `can.create` is explicit. Rows loaded through `include` are not filtered by the related model's policy either; query the related model directly when that matters. An insert must receive its tenant ownership from trusted server-side context. Dashild does not copy `organizationId` from the scope into new data. Before enabling create, make sure your server-side create flow sets the active organization itself; do not rely on a hidden form field or a value supplied by the browser. ## Custom auth If you do not use the generated session, return the tenant from `getCurrentUser`, or resolve it with `organizationOf` and `rolesOf` in `policies.ts`: ```ts export const policies = definePolicies({ organizationOf: async (user) => user.activeOrganizationId ?? null, rolesOf: async (user) => user.roles ?? [], resources: { // ... }, }); ``` `organizationOf` and `rolesOf` replace the values from `user`; they are not a fallback chain. ## Reference `apps/playground` in the repository is the end-to-end example: two organizations, an admin who can switch, a member pinned to their own, and policies that return `null` without a tenant. --- # Policies and security Source: https://dashild.vercel.app/guides/policies/ Security is not declared in the resource. The resource only says that it is scoped (`policy: { scope: "organization" }`); the server resolves the `where`, the permissions, and the roles. ## Fail closed The runtime denies a resource when: - the resource has no `policy`, or - `policies.ts` has no entry for its model, or - `scope` returns `null`. Two more rules matter in practice: - An entry without `scope` is treated as an empty filter, so it allows everything. Always declare `scope`. - `scope` must return a `where` object or `null`. Returning `undefined` (for example, a forgotten `return`) is not a denial and is easy to miss. ```ts import { definePolicies, hasRole, type CurrentUser } from "@dashild/core"; export const policies = definePolicies({ resources: { Customer: { scope: (ctx) => ({ organizationId: ctx.organizationId }), can: { create: (ctx) => hasRole(ctx, "ADMIN", "SALES"), update: (ctx) => hasRole(ctx, "ADMIN", "SALES"), delete: (ctx) => hasRole(ctx, "ADMIN"), }, }, }, }); ``` `definePolicies` requires the `resources` container: the model map alone is not a valid definition, and `doctor` looks for that property when it checks `policies.ts`. ## What the scope covers `scope` is applied to top-level Prisma operations: reads (`findMany`, `findFirst`, `findUnique`, `count`, `aggregate`, `groupBy`), writes (`update`, `updateMany`, `upsert`), and deletes. It is also applied to relation managers in the panel. It does **not** cover: - `create` / `createMany` — an insert cannot be constrained by a read filter, which is why creating a scoped row requires an explicit `can.create`. - Rows loaded through an `include`: Prisma resolves them in the same query, so they are not filtered by the related model's policy. Query the related model directly (or through `runtime.client(user)`) when that matters. The runtime does not copy a tenant id from the scope into inserted data. Your server-side create flow must set tenant ownership from the authenticated `PolicyContext` (or another trusted server-side source), and must not trust a tenant id sent by the browser. ## Organization and roles `PolicyContext` carries `user`, `organizationId`, and `roles`. The values come from `organizationOf` / `rolesOf` when those functions are defined in `policies.ts`; otherwise they come from `user.organizationId` / `user.roles`. It is one or the other, not a fallback chain: if `organizationOf` returns `null`, the context has `null`, even when `user.organizationId` is set. Returning them from `getCurrentUser` is enough for most apps: ```ts async function getCurrentUser() { const session = await auth.api.getSession({ headers: await headers() }); if (!session) return null; const user = await prisma.user.findUnique({ where: { id: session.user.id }, select: { id: true, email: true, name: true, organizationId: true, roles: true }, }); return user; } ``` Use `hasRole(ctx, "ADMIN", "SALES")` for readable predicates. A scoped resource cannot create unless `can.create` is explicit, because the runtime cannot infer which organization the new row belongs to. ## Defaults - `list`, `view`, `update`, and `delete` are allowed when there is no predicate for them. - `create` is denied when the scope is not empty and there is no `can.create`. - A declared action with `requires` is denied unless the policy has a predicate with that name. These are permission-predicate defaults, not a replacement for authentication, resource policy resolution, input validation, or the tenant scope. The scope limits which existing rows can be found or changed; it does not choose the organization for a newly inserted row. ## Actions Actions can require a permission declared here: ```ts table: { actions: [{ name: "refund", requires: "refund" }], } ``` ```ts Customer: { scope: (ctx) => ({ organizationId: ctx.organizationId }), can: { refund: (ctx) => hasRole(ctx, "ADMIN") }, } ``` The UI hides actions whose `requires` is false, and the server also denies them. ## Scoped Prisma client `withDashildScope` returns a Prisma extension with the active scope applied; the runtime mounts it with `prisma.$extends`. It lives in the server entry point: ```ts import { withDashildScope } from "@dashild/core/server"; ``` For custom server code, prefer `runtime.client(user)`: ```ts const client = runtime.client(user) as typeof prisma; const customers = await client.customer.findMany(); ``` `runtime.client` is typed as `unknown` so `@dashild/core` does not depend on your generated Prisma client; cast it once, as above. If your client does not support `$extends`, the runtime returns the plain Prisma client. For a direct extension: ```ts const client = prisma.$extends( withDashildScope({ resources, policies, user }), ); ``` The resource file never contains the `where`; that is the point. ## Rules - `policies.ts` is server-only by convention: nothing enforces it at build time, so never import it from a client component. - The client cannot influence the policy: server actions resolve it themselves. - Roles are strings; the app decides their names and how they are assigned. --- # Resources Source: https://dashild.vercel.app/guides/resources/ A resource is a serializable file. It describes the table, form, filters, navigation, and actions for a Prisma model. There are no pages to generate and no files to keep in sync. ```ts // src/dashild/resources/customer.ts import { defineResource } from "@dashild/core"; export const customerResource = defineResource({ model: "Customer", navigation: { label: "Customers", slug: "customers", group: "Sales", icon: "users", }, table: { searchable: ["name", "email"], columns: [ { field: "name", sortable: true }, { field: "email" }, { field: "status", format: "badge", tone: { ACTIVE: "green", LEAD: "danger" }, }, ], filters: [{ field: "status", type: "enum" }], }, form: { fields: [ { field: "name", type: "text", rules: { required: true } }, { field: "email", type: "email", rules: { required: true } }, { field: "status", type: "select" }, ], }, policy: { scope: "organization" }, }); ``` `dashild make:resource Customer` generates this file from the Prisma metadata and registers it in `panel.ts` and `policies.ts`. The file is write-once: the command never overwrites your edits. ## Navigation `label` is the sidebar label, `slug` is the URL segment under the panel route, and `group` groups resources in the sidebar. `icon` is resolved by the shell (`users`, `user`, `building`, `organization`, `file-text`, `settings`, `database`, `folder`, `chart`, `layout-dashboard`, `package`, `shopping-cart`, `tag`, `calendar`, `mail`, `briefcase`, `credit-card`, `truck`, `layers`), and the app can add its own in `src/dashild/icons.tsx`. ## Table - `columns`: field, optional label, `sortable`, `format`, `cell`, `display`, and `tone`. - `searchable`: fields used by the search box. Pagination, sorting, and filters run on the server. - `filters`: `boolean`, `enum`, `relation`, `text`, `number`, or `date`. - `pageSize`: optional page size. - `actions`: header or row actions (see below). `tone` accepts `accent`, `green`, `muted`, or `danger`; any other value renders the default outline badge. `format` accepts `badge`, `number`, `currency`, `date`, `datetime`, `json`, or `text`. Booleans and enums use `badge` by default. `number` and `currency` format with the panel locale; for `Decimal` money use `format: "currency", currency: "EUR"`. Scalar lists (`String[]`, `Int[]`...) render and edit as a JSON array. `cell` points to a component registered with `registerCell` (see [Customization](/guides/customization/)). For relations, set `field` to the relation name and `display` to the related field: ```ts { field: "organization", display: "name" } ``` ### Filters Declared filters render as a bar above the table: selects for `enum`, `relation`, and `boolean`, inputs for `text`, `number`, and `date`. Applying them submits a GET form, so the values stay in the URL and you can link to a filtered table (`?status=ACTIVE`). The server applies them; `relation` filters support many-to-one relations only, and `enum`/`text` compare exact values. Enum options come from the values in Prisma metadata; they are the same for all users. Relation options are loaded on the server for the current user and respect the active scope where that relation is scoped. ## Form Fields use the Prisma type by default. `rules` adds `required`, `min`, `max`, or a `pattern` string; `component` points to a field registered with `registerField`; `default` sets an initial value. ```ts form: { fields: [ { field: "name", type: "text", rules: { required: true, max: 120 } }, { field: "email", type: "email", component: "email" }, { field: "notes", type: "textarea" }, { field: "tags", type: "relation", relation: "tags", multiple: true, display: "name" }, ], } ``` `Bytes` fields render a file picker and are sent as base64. `createdAt` and `deletedAt` are shown in the table; `updatedAt`, `id`, and relation-owned foreign keys are omitted from the table and the form. `make:resource` also leaves audit fields (`createdAt`, `updatedAt`, `deletedAt`) out of the form. ## Relations - **o2m** (one-to-many): the parent detail page shows a `RelationManager` for the children. Create and edit are available; delete only when the child resource allows it, and detach only when the foreign key is optional. - **m2m** (many-to-many): the detail page allows attach and detach when the child resource permits it, and the form can use `type: "relation"` with `multiple: true`. The child model needs its own resource in `panel.resources`, and the manager needs `relationAction` wired in the route (the scaffold does it). Without rows or without that action, the manager is not rendered. Relation ids are re-checked on the server. A form or CSV import cannot connect a record to a row outside the related resource's policy scope, even if the id is guessed; the save returns a field error. Attach/detach requires update permission on the child, and o2m detach also verifies that the child belongs to that parent. ## Actions Actions are declared in the resource and handled on the server: ```ts table: { actions: [{ name: "export", label: "Export", placement: "header" }], } ``` ```ts // src/dashild/actions/index.ts import type { ActionHandler, CurrentUser } from "@dashild/core"; import { prisma } from "../../lib/prisma"; export const resourceActions: Record< string, Record> > = { Customer: { export: async ({ db, organizationId }) => { // `db` is the scoped Prisma client, typed as `unknown` in core. const client = db as typeof prisma; // Use `client.customer` here for the server-side export/query. return { ok: true, message: "Export started" }; }, }, }; ``` Declaring `table.actions` **replaces** the built-in create, view, edit, and delete actions; include them yourself if you still want them. Form actions behave the same way. An action can declare `requires` (checked against policies), `confirm`, `variant`, `placement` (`header` or `row`), and `href` for link actions. `variant` styles the button and the confirmation, not the row dropdown item. ## Doctor ```bash pnpm dashild doctor ``` It parses resources with Babel (without importing Next) and checks models, columns, filters, form fields, relations, `policy`, the `policies.ts` entry, action handlers, `requires` predicates, and duplicate slugs. It always reports the file; the line is included when the issue comes from a resource node. Some findings are warnings and do not affect the exit code. It exits with code 1 on errors, and also when no resource is found. It does not validate presentation details such as `navigation.label`, `format`, `tone`, or `placement`. --- # Stripe Source: https://dashild.vercel.app/guides/stripe/ Dashild does not call the Stripe API. The integration is a small helper that turns a Stripe id stored on a record into a dashboard link and runs it as a row action. No secret key, no webhook, no network request. Use it when your checkout or billing flow already stores `cus_...`, `sub_...`, or `in_...` ids and your team wants a shortcut from the admin to Stripe. ## 1. Store the id Add the field to the model: ```prisma title="prisma/schema.prisma" model Customer { id String @id @default(uuid()) name String stripeCustomerId String? } ``` `stripeActionHandler` uses `stripeCustomerId` by default; pass `field` for another column. ## 2. Declare the action ```ts title="src/dashild/resources/customer.ts" table: { columns: [{ field: "name", sortable: true }], actions: [ { name: "create", placement: "header" }, { name: "view", placement: "row" }, { name: "edit", placement: "row" }, { name: "delete", placement: "row" }, { name: "openInStripe", label: "Open in Stripe", placement: "row", }, ], }, form: { fields: [ { field: "name", type: "text", rules: { required: true } }, { field: "stripeCustomerId", type: "text" }, ], }, ``` ## 3. Register the handler ```ts title="src/dashild/actions/index.ts" import type { ActionHandler, CurrentUser } from "@dashild/core"; import { stripeActionHandler } from "@dashild/core/server"; export const resourceActions: Record< string, Record> > = { Customer: { openInStripe: stripeActionHandler({ type: "customer", field: "stripeCustomerId", mode: "test", }), }, }; ``` The handler reads the record with the scoped Prisma client, so a record outside the user's policy scope is not reachable. If the field is empty, the action returns an error instead of a broken link. ## Dashboard URLs `stripeDashboardUrl` is a pure helper, exported from `@dashild/core`: ```ts import { stripeDashboardUrl } from "@dashild/core"; stripeDashboardUrl({ type: "customer", id: "cus_123", mode: "test" }); // https://dashboard.stripe.com/test/customers/cus_123 ``` Supported types: `customer`, `subscription`, `invoice`, `payment`, `product`, `price`. `mode: "test"` adds `/test` to the path; the default is live. ## Limitations - **No sync**: the ids must come from your own checkout, billing, or webhook flow. This package does not create customers or subscriptions. - **No webhook**: nothing is updated from Stripe events. - A fake id still produces a valid URL; Stripe shows its own 404. Store real ids before shipping. - The action is a link (`href`), not a server mutation. The `shop` starter includes a working example on customers. --- # Dashboard widgets Source: https://dashild.vercel.app/guides/widgets/ The dashboard home combines **widgets** with the resource cards. A widget is one file that returns data; the panel renders it. The three types mirror Filament's stats overview, chart, and table widgets; custom widgets are not included in this alpha. | Type | What it shows | | --- | --- | | `stats` | A row of stat cards: value, description, icon, color, optional sparkline | | `chart` | A line, area, bar, pie, or doughnut chart | | `table` | A small read-only table with resource-style columns | Widgets are server-rendered. Their `data()` function runs on the server with the same scoped Prisma client as an action handler, and only the resulting values are sent to the browser. ![A dashboard with stats, a chart, a table, and the resource cards](/images/examples/shop/dashboard.png) ## Create a widget ```bash pnpm dashild make:widget RevenueOverview --stats pnpm dashild make:widget OrdersChart --chart bar pnpm dashild make:widget LatestOrders --table ``` The command writes `src/dashild/widgets/.ts` and registers the export in `panel.ts`. The file is **write-once**: running the command again never overwrites your work. | Flag | Meaning | | --- | --- | | `--stats` / `--info` | Stat cards (default) | | `--chart [type]` | Chart; type is `line` (default), `area`, `bar`, `pie`, or `doughnut` | | `--table` | Table | | `--width ` | `full`, `half`, `third`, or `two-thirds` | | `--dir ` | Widgets folder; defaults to `src/dashild/widgets` | | `--no-register` | Write the file without touching `panel.ts` | | `--dry-run` | Print the file without writing it | The panel keeps them next to the resources: ```ts title="src/dashild/panel.ts" export const panel = definePanel({ title: "Admin", path: "/admin", resources: [postResource], widgets: [revenueOverviewWidget, ordersChartWidget, latestOrdersWidget], auth: { getCurrentUser, signOut }, }); ``` ## Stats widgets A stats widget returns an array, one entry per card: ```ts title="src/dashild/widgets/revenue-overview.ts" import { defineWidget } from "@dashild/core"; interface ScopedClient { order: { count(args?: { where?: Record }): Promise; aggregate(args: { where?: Record; _sum: { total: true }; }): Promise<{ _sum: { total: unknown } }>; }; } export const revenueOverviewWidget = defineWidget({ type: "stats", title: "Store overview", description: "Live numbers from the shop.", width: "full", async data({ db }) { const client = db as ScopedClient; const [revenue, orders] = await Promise.all([ client.order.aggregate({ where: { status: { in: ["PAID", "SHIPPED"] } }, _sum: { total: true }, }), client.order.count(), ]); return [ { label: "Revenue", value: `€${Number(revenue._sum.total ?? 0).toFixed(2)}`, description: "Paid and shipped orders", descriptionIcon: "trending-up", color: "success", }, { label: "Orders", value: orders, description: "All orders", descriptionIcon: "shopping-cart", }, ]; }, }); ``` Each item accepts: - `label` and `value` (required). - `description` and `descriptionIcon` (a built-in icon name or one from `src/dashild/icons.tsx`). - `color`: `default`, `info`, `success`, `warning`, or `danger`. - `chart`: an array of numbers for a small sparkline. - `href`: makes the whole card a link. ## Chart widgets A chart returns `labels` and one or more `datasets`, the same shape Chart.js uses. The `ScopedClient` interface is the same idea as the stats example: declare only the delegates this widget calls. ```ts title="src/dashild/widgets/orders-chart.ts" export const ordersChartWidget = defineWidget({ type: "chart", chart: "doughnut", title: "Orders by status", description: "Current orders grouped by state.", width: "half", async data({ db }) { const client = db as ScopedClient; const groups = await client.order.groupBy({ by: ["status"], _count: { _all: true }, }); const counts = new Map( groups.map((group) => [group.status, group._count._all]), ); return { labels: ["Pending", "Paid", "Shipped", "Cancelled"], datasets: [ { label: "Orders", data: ["PENDING", "PAID", "SHIPPED", "CANCELLED"].map( (status) => counts.get(status) ?? 0, ), }, ], }; }, }); ``` - `chart`: `line`, `area`, `bar`, `pie`, or `doughnut`. - `labels`: one label per data point. - `datasets`: each dataset has a `label`, a `data` array, and an optional `color`. Without a color, the theme's chart palette is used. - Pie and doughnut charts use the first dataset; each label becomes a slice. Charts render with [Recharts](https://recharts.org) on the client. The data is plain JSON, so the widget itself stays on the server. ![The chart and table widgets on the shop dashboard](/images/examples/shop/dashboard.png) ## Table widgets A table widget returns `columns` and `rows`. Columns use the same format as a resource table. Declare the delegates you query on `ScopedClient` as in the stats example: ```ts title="src/dashild/widgets/latest-orders.ts" export const latestOrdersWidget = defineWidget({ type: "table", title: "Latest orders", width: "half", empty: "No orders yet.", columns: [ { field: "number", label: "Number" }, { field: "customer", label: "Customer", display: "name" }, { field: "status", label: "Status", format: "badge", tone: { PENDING: "accent", PAID: "green", CANCELLED: "danger" }, }, { field: "total", label: "Total", format: "currency", currency: "EUR" }, { field: "createdAt", label: "Created", format: "datetime" }, ], async data({ db }) { const client = db as ScopedClient; const rows = await client.order.findMany({ take: 5, orderBy: { createdAt: "desc" }, include: { customer: { select: { id: true, name: true } } }, }); return rows.map((row) => ({ id: row.id, number: row.number, customer: row.customer ? { id: row.customer.id, display: row.customer.name } : null, status: row.status, total: row.total, createdAt: row.createdAt, })); }, }); ``` `format` supports `text`, `number`, `currency`, `date`, `datetime`, `badge`, and `json`. For a relation column, map the row to `{ id, display }` and set `display` on the column, exactly as above. `empty` is the text shown when there are no rows. ## The data context `data()` receives: | Value | Description | | --- | --- | | `db` | Prisma extended with the user's policy scope | | `user` | The signed-in user (`id`, `email`, `name`, `organizationId`, `roles`) | | `locale` | `en` or `es` | | `now` | A stable `Date` for ranges such as “the last 30 days” | `db` is typed as `unknown` because core does not depend on a generated Prisma client. Cast it to the delegates the widget uses, like the action handlers do. **Security:** `db` applies the same policy scope as the resource tables. A widget that counts orders counts only the orders the user can read. Models without a Dashild resource pass through unchanged; a resource with a missing policy fails closed. `canView` hides a widget for some users before `data()` runs: ```ts canView: ({ user }) => user.roles?.includes("ADMIN") ?? false, ``` It is a UI convenience, not a security boundary. The scope on `db` is the security boundary. ## Layout - `width`: `full` (default for stats and tables), `half` (default for charts), `third`, or `two-thirds`. - `sort`: lower numbers render first; ties keep the panel order. - Stats widgets lay their cards out automatically: one to four fit in a row on wide screens and stack on mobile. ## Limits in this alpha - Widgets load on every dashboard request; there is no polling or lazy loading. - Custom React widgets are not supported yet: use stats, charts, and tables. - Dashboard-wide filters are not available yet; query the range inside `data()`. - A widget error shows a generic “could not be loaded” card and logs the error on the server, so one broken widget does not take down the dashboard. ## Troubleshooting - **The widget does not appear**: check that it is in `panel.ts` and that `canView` returns true. - **The chart is empty**: `labels` and every dataset's `data` must be arrays of the same length. - **A relation column is blank**: return `{ id, display }` for that field and set `display` on the column. - **The numbers ignore the tenant**: the widget is not using `db` from the context, or the model has no policy entry. - **Pie colors are all the same**: omit `color` to use the palette; a dataset `color` is applied to the whole series. --- # CLI reference Source: https://dashild.vercel.app/reference/cli/ The `dashild` binary lives in `@dashild/cli`, which you install in the project: ```bash pnpm add -D @dashild/cli@alpha pnpm dashild ``` `pnpm add -D` installs the CLI as a development dependency: it is a tool for building and checking your app, not code your production server needs to run. `pnpm dashild` runs the locally installed binary, keeping the command version consistent with the project. `pnpm create dashild` is a different package (`create-dashild`) and only scaffolds new apps. Global option: `--lang en|es` (or `DASHILD_LANG`). It translates the main messages; some command output (`make:action`, `ui:add`, `eject`, `doctor`) is still English, and any value other than `es` falls back to `en`. ## `init` ```bash pnpm dashild init --auth better-auth --yes ``` Adds the panel to an existing Next.js app. It reads `dashild-metadata.json`, so run `prisma generate` first (or pass `--metadata`). It prints the plan first; `--yes` writes, `--dry-run` never writes. Without `--force` it refuses to overwrite existing files. Use `init` once to create the panel's connection points: configuration, policies, server runtime, and the Next.js route. It is a scaffolding command, not a migration runner or a replacement for your app's layout and middleware. | Option | Purpose | | --- | --- | | `--auth ` | Auth integration. Defaults to `none`. | | `--path ` | Mount route. Avoids an existing `app/admin/page.tsx`. | | `--metadata ` | Explicit `dashild-metadata.json`. | | `--cwd ` | Project root. Defaults to the current directory. | | `--yes` | Apply the plan. | | `--dry-run` | Show the plan only. | | `--force` | Overwrite the generated files. | | `--tenancy` | Add the Organization model, tenant session, switch action, and sidebar switcher. Requires Better Auth and a schema without auth models. | It writes `panel.ts`, `policies.ts`, `actions/index.ts`, `icons.tsx`, `runtime.ts`, `server.ts`, `registry.tsx`, and the mount route. With `--auth better-auth` it also writes the auth files, models, and env keys, and appends missing keys to `.env.example`. It does not touch `middleware.ts`/`proxy.ts`, the root layout, `next.config`, or your `.env`. `--force` overwrites the generated files (including the auth ones) but it does not bypass a route conflict when you pass an explicit `--path`; choose another route instead. Running `init` a second time fails on the files it already wrote, and `--force` rewrites them. ## `upgrade` ```bash pnpm dashild upgrade --check pnpm dashild upgrade --dry-run pnpm dashild upgrade ``` Updates the four `@dashild/*` packages to the npm `latest` tag, installs them, runs `prisma generate`, and records the version in `dashild.json`. It never rewrites the generated glue; it lists the version marker of each generated file so you can review the ones from an older CLI. See [Upgrading](/getting-started/upgrading/). Options: `--tag alpha`, `--to `, `--check`, `--dry-run`, `--no-install`, `--no-generate`, `--cwd`. ## `make:resource` ```bash pnpm dashild make:resource Customer ``` Reads the Prisma metadata and writes `src/dashild/resources/customer.ts`. The file is write-once: it never overwrites an existing resource. Use this after adding a Prisma model when you want Dashild to create the first table/form definition for it. Then edit the generated file to choose the fields and permissions your app actually needs. - Skips `id`, `@updatedAt`, and foreign keys written by a relation (Prisma marks them read-only). - Includes `Bytes` fields, scalar lists as a JSON array, and m2m relations as a multiselect. o2m relations are managed from the child's detail page. - Adds the resource to `panel.resources` and a fail-closed entry to `policies.ts`. - `--no-register` leaves `panel.ts` and `policies.ts` untouched. - `--dir`, `--metadata`, `--cwd`, and `--dry-run` are available. ## `make:widget` ```bash pnpm dashild make:widget RevenueOverview --stats pnpm dashild make:widget OrdersChart --chart bar pnpm dashild make:widget LatestOrders --table ``` Writes `src/dashild/widgets/.ts` and adds the export to `panel.widgets`. The file is write-once. The default type is `stats`; `--info` is an alias. | Option | Purpose | | --- | --- | | `--stats` / `--info` | Stat cards | | `--chart [type]` | Chart: `line`, `area`, `bar`, `pie`, `doughnut` | | `--table` | Table widget | | `--width ` | `full`, `half`, `third`, `two-thirds` | | `--dir ` | Widgets folder | | `--no-register` | Leave `panel.ts` untouched | | `--dry-run` | Print the file without writing it | See [Dashboard widgets](/guides/widgets/) for the data contract and examples. ## `make:action` ```bash pnpm dashild make:action Customer export ``` Appends a typed handler stub to `src/dashild/actions/index.ts`. It does not edit the resource: declare the action in `table.actions` or `form.actions`. Running it twice does not duplicate the handler, and `dashild doctor` recognizes the generated assignment. Use it when an action needs server-side behavior that normal create/edit/delete cannot express. The stub is only a starting point: implement the operation and return a suitable result before exposing it to users. Options: `--cwd`, `--dir` (actions folder). ## `doctor` ```bash pnpm dashild doctor pnpm dashild doctor --json ``` Parses resources with Babel and compares them with the metadata: model, slug, columns, filters, form fields, relations, `policy`, the `policies.ts` entry, action handlers, `requires` predicates, and duplicate slugs. It reports the file and the line when the issue has one, and exits with code 1 on errors. Findings such as a column without a form field are warnings and do not change the exit code. It also exits with 1 when there is no resource at all. `--json` is for CI. Run `doctor` after generating or editing resources, and before opening a pull request. It reports likely wiring and metadata errors; it does not execute the app, connect to the database, or replace TypeScript and test runs. Options: `--cwd`, `--dir`, `--metadata`, `--policies`, `--actions`, `--json`. ## `skill install` ```bash pnpm dashild skill install pnpm dashild skill install --agent claude ``` Copies the Dashild agent skill into `.claude/skills/dashild` and/or `.opencode/skills/dashild`, and adds a short pointer to `AGENTS.md`. Reinstalling replaces the skill and refreshes the block. See [AI assistant](/getting-started/ai/). ## `ui:add` ```bash pnpm dashild ui:add avatar-cell email-field ``` Copies cell and field templates to `components/dashild/` (or `--dir`). It does not edit `registry.tsx`; it prints the exact call to add, for example `registerCell("avatar", AvatarCell)`. Options: `--force`, `--dry-run`, `--dir`, `--cwd`. Available templates: `avatar-cell`, `email-field`. An unknown name is reported and the command still exits with code 0. Use `ui:add` to copy a starter React component into your app. The printed registration line is a separate step: add it to `registry.tsx`, then reference the registered name from the resource definition. ## `eject` ```bash pnpm dashild eject pnpm dashild eject --yes ``` Removes the files written by `init`: the panel files, the mount route, and the `dashild` script. It keeps resources, auth files, the Prisma generator, and dependencies, and lists the ones it can detect. Without `--yes` it only prints the plan. Options: `--cwd`, `--path` (when the route cannot be read from `panel.ts`), `--dry-run`. Use `eject` when you intentionally want to remove Dashild's generated glue. It does not uninstall packages, remove auth, or delete resource definitions. Review the preview and create a backup or Git checkpoint before confirming. ## Exit codes `0` success; `1` a failed check, a refused overwrite, a missing metadata file, or a validation error. A `doctor` run with no resources also exits with 1. --- # Server API Source: https://dashild.vercel.app/reference/server-api/ Client components receive serializable data; everything that reads or writes the database lives in this entry point. `@dashild/core` never imports it, so the client bundle stays small. ```ts import { createDashildRuntime, resolvePolicy, withDashildScope, } from "@dashild/core/server"; ``` ## Runtime `createDashildRuntime(options)` returns the object the panel uses. It needs the app's Prisma client, the generated metadata, the resources, the policies, and (optionally) the action handlers: ```ts export const runtime = createDashildRuntime({ prisma, metadata, resources: panel.resources, policies, locale: panel.locale, actions: resourceActions, }); ``` | Method | What it does | | --- | --- | | `list(resource, raw, user)` | Applies the whitelist, the scope, and the DTO. Returns `{ rows, total, params }`. | | `record(resource, id, user)` | One row, scoped and converted, or `null`. | | `formOptions(resource, user, recordId?)` | Enum values and relation options for the form. | | `filterOptions(resource, user)` | Enum values and relation labels for the filter bar. | | `exportCsv(resource, raw, user)` | CSV of the current view (5,000-row cap). | | `importCsv(resource, csv, user)` | Creates rows from CSV (1,000-row cap). | | `save({ slug, id?, values }, user)` | Validates, writes, and maps Prisma errors. | | `remove({ slug, id }, user)` | Deletes through the policy. | | `runAction({ slug, name, id?, values?, data? }, user)` | Runs a declared action handler. | | `relationManagers(parent, id, user)` | Loads child tables for the detail page. | | `relationAction(input, user)` | Attach, detach, associate, dissociate, delete. | | `client(user)` | Prisma extended with the user's scope; typed `unknown`. | `client(user)` is `unknown` so core does not depend on your generated client. Cast it once in app code: ```ts const client = runtime.client(user) as typeof prisma; ``` ## Policies | Function | Result | | --- | --- | | `resolvePolicy(resource, policies, user)` | `{ ok: true, policy }` or `{ ok: false, reason }`. Reasons: `no-policy`, `no-policies`, `no-resource-policy`, `scope-denied`. | | `canPerform(policy, operation, values?)` | Permission-predicate defaults: `create` needs an explicit predicate when the scope is not empty; other operations are allowed without one. Authentication and policy resolution still apply. | | `canRunAction(policy, action)` | Deny by default when `requires` has no matching predicate. | | `PolicyDeniedError` | Page-loading operations can throw this for denied resources; the panel turns it into a 404. Mutation/action methods may instead return `{ ok: false }`. | ## Scoping Prisma ```ts import { withDashildScope } from "@dashild/core/server"; const client = prisma.$extends( withDashildScope({ resources, policies, user }), ); ``` It applies the resource scope to top-level reads, updates, and deletes. Inserts and relation `include`s are not covered; use `runtime.client(user)` in custom server code so the policy is applied once per request. ## Lists | Function | Purpose | | --- | --- | | `normalizeListParams(resource, raw)` | Whitelists page, sort, search, and filters. | | `buildListQuery(resource, model, params)` | Builds `where`, `orderBy`, `skip`, `take`, and `include` from the resource. | | `toDTO(row, model, resource, context)` | Applies each field's `dto` and flattens relations to `{ id, display }`. | | `listContext(metadata, locale)` | The mapping context used by the DTO. | ## Writes | Function | Purpose | | --- | --- | | `buildWriteSchema(resource, model, context, operation)` | Zod schema from the form fields, rules, and metadata. | | `parseWriteInput(resource, model, context, input, operation)` | Returns `{ ok: true, data }` or `{ ok: false, fieldErrors }`. | | `toPrismaData(resource, model, context, values, operation)` | Converts values (`BigInt`, `Decimal`, `DateTime`, `connect`/`disconnect`). | | `flattenZodError(error)` | Field-indexed messages for the form. | | `coerceRecordId(field, value)` | Casts a route id to the model's id type. | | `formatPrismaError(error, locale)` | Maps P2002 unique conflicts, P2003 relation conflicts, and P2025 missing records to field errors or a message; other codes use the generic write error. | ## Types `DashboardRuntimeOptions`, `DashboardRuntime`, `ResolvedPolicy`, `PolicyResolution`, `NormalizedListParams`, `ListQuery`, `FormOption`, `RelationManagerData`, `RelationActionInput`, `RuntimeSaveResult`, and `WriteError` are exported from the same entry point. --- # Templates Source: https://dashild.vercel.app/reference/templates/ `create-dashild` ships three starters: - `basic`: no extra files. The dashboard shows the empty state; with the default `--auth better-auth` you also get the login, signup, and reset pages. - `blog`: posts, categories, tags, comments, and an editorial workflow. Authors only see their own posts; admins moderate everything (`ana@blog.test` admin, `bruno@blog.test` / `carla@blog.test` authors; password `dashild123`). - `demo`: users, posts, and labels, with permissive demo policies and a seed (`ana@acme.test` / `dashild123`). - `shop`: catalog, stock, suppliers, customers, orders, and order items. Any signed-in staff member manages it (`ana@shop.test` / `dashild123`). - `saas`: organizations, members, and projects, isolated by tenant. It enables tenancy for you (`ana@acme.test` is an admin, `carla@beta.test` a member of another organization; password `dashild123`). ```bash pnpm create dashild@latest my-app --template demo ``` Here, `--template demo` chooses the seeded demo starter, `my-app` names the new folder, and `pnpm create` runs the published generator. Omitting `--template` lets the generator ask which starter to use. A starter can also be a local folder or come from GitHub: ```bash npx create-dashild@latest my-app --template ./starters/crm npx create-dashild@latest my-app --template local:../starters/crm npx create-dashild@latest my-app --template github:acme/dashild-crm#main ``` npm templates are not supported in the current alpha. The `--template` value is a local path (`./...`, an absolute path, or `local:`) or a `github:` spec. ## Format A template is a folder with `template.json` and project files: ```json { "name": "crm", "version": "1.0.0", "dashild": ">=0.1.0-alpha.15", "prisma": { "provider": ["postgresql"] }, "requires": { "auth": ["better-auth"] }, "extend": { "User": ["role Role @default(USER)"] }, "env": ["STRIPE_SECRET"] } ``` | Field | Purpose | | --- | --- | | `name`, `version` | Identity recorded in `dashild.json`. | | `dashild` | Supported Dashild semver range. | | `prisma.provider` | Allowed database providers. | | `requires.auth` | Required auth integration (array). | | `requires.tenancy` | `true` needs `--tenancy`; `false` forbids it. | | `overwrite` | Generated files this starter replaces on purpose (under `src/`). | | `extend` | Extra Prisma fields for an existing model. | | `dependencies`, `devDependencies` | Extra app dependencies. | | `env` | Env keys appended to `.env.example` when missing. | ## Files - `prisma/models.prisma` is appended to the schema inside a marker block. If the same template is applied again, the command fails with “already applied” instead of duplicating models. The marker detects the reapplication; it does not make it idempotent. - `extend` adds fields to models that already exist (for example `User`). Fields that are already present are skipped silently. - A model or enum whose name already exists in the schema is a hard error. - `src/dashild/resources/*.ts` are copied and registered in `panel.ts`. - `src/dashild/policies.ts` replaces the default policies, and files listed in `overwrite` replace the generated glue (`blog` uses it for `session.ts` and `actions/index.ts`). - `prisma/seed.ts` runs only when the install and migration steps succeeded; with `--seed` but no migration it stays pending. - `env` keys are appended to `.env.example` with an empty value; values are yours to fill in. Templates run after the Better Auth models are created, so a template can extend `User` safely. ## Package pinning `dashild.json` records the chosen template, auth, database, route, and creation date. It does not store the installed package versions. `create-dashild` pins `@dashild/*` in the generated `package.json` to the stack version it ships with (the `dashildPackages` field of its own manifest). The scaffolder can move ahead of the stack for its own fixes; the generated app keeps the published packages it was tested with. A template's `dependencies` are merged after that pinning, so a template can override `@dashild/*` and break the guarantee. Do not declare `@dashild/*` packages in a template. `create-dashild` is published with both `latest` and `alpha`; the docs use `pnpm create dashild@latest`. --- # Troubleshooting Source: https://dashild.vercel.app/troubleshooting/ When something fails, start with the exact command output and identify which stage failed: dependency installation, Prisma generation/migration, Dashild scaffolding, or the Next.js dev server. These stages are separate; rerun only the step that needs attention rather than deleting generated files or the database. Useful checks: ```bash pnpm prisma generate pnpm dashild doctor pnpm dev ``` `prisma generate` refreshes the generated client and Dashild metadata after a schema change. `dashild doctor` checks resource and policy wiring without connecting to the database. `pnpm dev` starts the app so you can reproduce a runtime or browser problem. ## The panel does not hydrate on 127.0.0.1 Next 16 only allows `localhost` for dev assets and HMR by default. Open `http://localhost:3000`, not `http://127.0.0.1:3000`, or add the origin to `next.config.ts`: ```ts const nextConfig: NextConfig = { allowedDevOrigins: ["127.0.0.1", "localhost"], }; ``` The generated config already includes both. ## `dashild init` cannot find the metadata `init` reads `dashild-metadata.json`, which the `dashild` Prisma generator writes. Run `pnpm prisma generate` before `init`. If the file lives outside the standard paths, pass it explicitly: ```bash pnpm dashild init --auth better-auth --metadata prisma/generated/dashild/dashild-metadata.json ``` ## The theme switch does not appear The switch needs both `theme.toggle: true` and a `themeAction` prop. The route generated by `dashild init` passes it; a hand-written route must do the same. See [Customization](/guides/customization/#theme-switch). ## `better-sqlite3` has the wrong ABI Native bindings are compiled for the Node that runs the install script. With pnpm there is no bundled `node-gyp`, so the prebuild must match. Install with the Node that runs the app and set the target: ```bash PATH="$(dirname "$(node -p process.execPath)"):$PATH" \ npm_config_target="$(node -p process.versions.node)" \ npm_config_arch="$(node -p process.arch)" \ pnpm install ``` The scaffolder does this for you. If you use a version manager, make sure it does not resolve a different Node inside `node_modules`. ## Login fails with an origin error `BETTER_AUTH_URL` must match the browser origin exactly, including the port: ```bash BETTER_AUTH_URL="http://localhost:3000" ``` If you open the app from another host or port, update the variable and restart the dev server. ## Prisma cannot connect If you use lerd, check that the database service is running; idle suspension can stop it. `lerd service start postgres` or `lerd service start mysql` brings it back. For a hosted database, check `DATABASE_URL` and `DIRECT_URL` and whether the provider requires SSL. ## Fonts look like Times New Roman `--font-sans` is self-referencing or undefined. Define a real stack in `globals.css`: ```css @theme inline { --font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; } ``` ## Tailwind classes from the shell are missing Tailwind must scan the package build. Add the source to your global CSS: ```css @source "../../node_modules/@dashild/admin/dist"; ``` Adjust the relative path if your CSS file is in a different folder. ## Password reset emails are not sent `src/lib/email.ts` logs the email in development and throws in production until you configure a provider. Set `RESEND_API_KEY` and `EMAIL_FROM` (uncomment them in `.env`), or replace `sendEmail` with your own transport. ## A resource returns 404 The policy entry is fail-closed. Check that the resource declares `policy: { scope: ... }`, that `policies.ts` has an entry for the model under `resources`, and that `scope` returns a `where` fragment instead of `null`. Run `pnpm dashild doctor` for the exact file and line. ## A project shows no resources in `doctor` `doctor` exits with code 1 when it finds no resources. Create one with `pnpm dashild make:resource ` or point `--dir` at the right folder.