Create FasterCreate Faster
Business

Org Dashboard (Next.js)

Dashboard with auth, RBAC, admin panel, and example CRUD. Ships as a turborepo with a Next.js web app, a Node batch worker, and shared packages.

A TanStack Start variant generates the same dashboard with a TanStack Start web app instead of Next.js.

Composition

Apps:

Project addons:

Architecture

Turborepo structure

apps/
  web/              # Next.js app
  batch/            # Node worker
packages/
  api/              # tRPC routers
  auth/             # Better Auth config + permissions + types
  db/               # Drizzle schema + client
  ui/               # shadcn components
  config/           # Shared tsconfig
scripts/
  local-setup.ts    # One-command local bootstrap (env, docker, schema, seed)
  seed.ts           # Idempotent, flag-driven database seeder

Web app

src/
├── app/
│   ├── layout.tsx                        # Root layout with AppProviders + Toaster
│   ├── (auth)/
│   │   ├── layout.tsx                    # Auth guard (redirect if logged in)
│   │   └── login/
│   │       ├── page.tsx
│   │       └── login-form.tsx            # Email/password login form
│   └── (dashboard)/
│       ├── layout.tsx                    # Sidebar + auth guard + session check
│       ├── page.tsx                      # Dashboard home (contact count, or a no-access note)
│       ├── admin/
│       │   ├── users/
│       │   │   ├── page.tsx              # User list, one page per URL (admin only)
│       │   │   └── [id]/
│       │   │       ├── page.tsx          # User detail
│       │   │       └── user-detail.tsx   # Edit user + generate password
│       │   └── roles/page.tsx            # Editable roles + permission matrix (admin only)
│       ├── contacts/
│       │   ├── page.tsx                  # Contact list, one page per URL
│       │   └── [id]/page.tsx             # Contact detail + edit
│       └── profile/
│           ├── layout.tsx                # Tab navigation + ViewTransition
│           ├── page.tsx                  # Redirect → /profile/account
│           ├── account/page.tsx          # Account info + edit name
│           ├── security/page.tsx         # Change password
│           ├── sessions/page.tsx         # Active sessions + revoke
│           └── preferences/page.tsx      # Theme switcher
├── components/
│   ├── admin/                            # Create user dialog, user actions, user table
│   ├── contacts/                         # Contact dialog, form, table
│   ├── navigation/                       # Sidebar, header, breadcrumbs, nav-user dropdown, command palette
│   ├── table-pagination.tsx              # PagedList: empty state, page past the end, or rows with range, page size and previous/next
│   ├── profile/                          # Account form, security form, session list, preferences, tab nav
│   ├── can.tsx                           # Permission gate component
│   └── query-boundary.tsx                # Suspense + ErrorBoundary + QueryErrorResetBoundary
├── hooks/
│   ├── use-page-params.ts                # Reads and writes the page and page size in the URL
│   └── use-permission.ts                 # The permission list of the caller, with a three-state verdict
├── lib/
│   └── constants.ts                      # Route definitions with required permissions
└── styles/
    └── globals.css                       # Slide animations for ViewTransition

API package (packages/api)

src/
├── root.ts                   # App router (user, contact, session, search)
├── trpc.ts                   # tRPC init with auth context + headers
├── pagination.ts             # Page and page size validation shared by the routers and the web app
├── page-query.ts             # One page of a table, newest first (server only)
├── search.ts                 # SEARCHABLE_TYPES: the contacts and users the palette finds
├── search-engine.ts          # The shape of a searchable type and the loop that runs them
├── search-query.ts           # Minimum length, maximum length and input of search.records
├── text-match.ts             # containsText: plain-text, case-insensitive match on your database
├── middleware/
│   └── rbac.ts               # adminProcedure + permissionProcedure(resource, action)
└── router/
    ├── user.ts               # me, create, list (paginated), count, getById, edit, generatePassword
    ├── contact.ts            # list (paginated), getById, create, update, delete, count
    ├── session.ts            # list, revoke, revokeOthers
    └── search.ts             # records: the groups of records the palette shows

Auth package (packages/auth)

src/
├── auth.ts                   # Better Auth config (admin plugin + the guard in front of it, drizzle adapter)
├── auth-client.ts            # Client with adminClient (ac/roles) + inferAdditionalFields
├── permissions.ts            # Business vocabulary + the compiled admin role of the plugin
├── role-permissions.ts       # What a role may do, read from the database on every request
├── role-management.ts        # Create, edit and delete roles
├── role-assignment.ts        # Assign a role, keep one administrator
├── guard-administrators.ts   # Guards the plugin endpoints that write a role, a ban or a removal
├── role-store.ts             # The writes that need a transaction (PostgreSQL)
├── default-roles.ts          # The roles a fresh database starts with
├── types.ts                  # Session type via auth.$Infer.Session
└── password.ts               # Cryptographic password generation

What's included

Authentication

Email/password login with Better Auth. Public sign-up is closed (emailAndPassword.disableSignUp, so /api/auth/sign-up/email is rejected): accounts are created by admins, or by the seed. The admin plugin powers account administration, ban/unban, and session management, and the roles of the database sit next to it. Auth layout redirects authenticated users away from login. Dashboard layout requires authentication and a valid role through requireSession() (src/lib/auth/session.ts); pages that prefetch protected data call it before the prefetch, because a layout and its page render in parallel and an anonymous visit must redirect without a failed query. Pages that prefetch an admin-only or permission-gated query call requireAdmin() (non-admins are redirected home) or requirePermission() (not-found page) in the same place. The dashboard home asks for no permission: it renders for every signed-in role, so a role that holds none lands on a page that says it has no access instead of a not-found page, and the page prefetches the contact count only when hasPermission(...) says the role may read contacts.

Role-based access control

A single-tenant RBAC whose roles are data. The code declares the vocabulary (businessStatement in packages/auth/src/permissions.ts: the contact actions) and the compiled admin role of the Better Auth admin plugin, which holds account administration (user, session) and every business action. What every other role may do is read from the roles and role_permissions tables on each request, so a change applies to the next request of everyone who holds the role, with no deployment. Three roles ship by default, written by db:roles (which local-setup runs) into a database that has no role yet:

  • admin — full user/session management + all contact actions (compiled, never edited)
  • user (default) — full CRUD on contact, no user management
  • manager — contact: ['read'] only, a read-only example role

Enforcement is on both sides: the server gates data routes with permissionProcedure(resource, action) (tRPC), and the UI gates affordances with the <Can> component / usePermission hook plus permission-filtered navigation, from the permission list the dashboard layout resolves on the server. An administrator edits the role matrix at /admin/roles: tick a box to grant a permission, clear it to revoke it, create a role, delete a role nobody holds. Only the admin role manages roles, and a stored permission can only name a business resource, so a role created at runtime never gains account administration. A role is assigned as exactly one id that exists, on every path (the dashboard, auth.api.* and the /api/auth/admin/* endpoints), and the last administrator can never be demoted, banned or removed, even when two administrators try at once (a transaction with a lock on PostgreSQL). The generated docs/agents/auth.md covers it in detail (see Agent Context).

Admin panel

User list with clickable rows linking to detail pages, one page at a time (see Paginated lists). Creating a user never asks for a password — user.create generates one server-side and returns it once. User detail allows editing name, first name, last name, phone, and regenerating one-time passwords (visible once, must be copied). User actions include role assignment (admin and every role of the database, so a role created at runtime is assignable at once) and ban/unban, on every account but your own: the signed-in admin gets no actions on their row and no role select on their page, and the server refuses banning, removing or changing the role of yourself (Better Auth refuses the first two; the refuseOwnRoleChange plugin in packages/auth/src/refuse-own-role-change.ts the third) with a 400 and a message.

CRUD example (Contacts)

Full create, read, update, delete for contacts. Contact form with validation (TanStack Form + Zod). The email, phone, company and notes are optional: the form and the contact router accept an empty one and the router stores it as null. Contact list with link to detail/edit page, one page at a time (see Paginated lists). A failed mutation shows the server's message in a toast.

Paginated lists

contact.list and user.list return the rows of one page, never the whole table, and contact.count and user.count return the total. The page is in the URL (/contacts?page=2&pageSize=25), so a page can be bookmarked and the back and forward buttons walk through the pages.

  • packages/api/src/pagination.ts is the one place that validates page (a whole number from 1 to 10,000) and pageSize (10, 25, 50 or 100). A missing or invalid value is the first page, or 10 rows, instead of an error or an unbounded read. The router input, the server prefetch and the web app all parse with it, so they ask for the same page. Offset pagination slows down with depth, so a table that needs to reach deeper rows should page by a cursor.
  • packages/api/src/page-query.ts orders rows newest first, with the id as a tie-break, so a row never appears on two pages or on none while you page. Both tables have an index on (created_at, id) for that order.
  • The total is its own count query, so changing page does not count again; a mutation that adds or removes a row invalidates it.
  • The page prefetches the page the URL names and dehydrates that one page. A page past the end shows an empty state with a button to the last page.
  • PagedList (src/components/table-pagination.tsx) renders the empty state, the page past the end, or the rows with a pager: range and total, a page size select and previous/next buttons. A new list calls usePageParams() for the page, asks for its rows with { page, pageSize } and for its count, and renders its table inside PagedList.

Command palette

A search field under the logo in the sidebar, or Ctrl+K (Cmd+K on macOS), opens a command palette. It lists the pages the role may open, from the same ROUTES table and permission filter as the sidebar, and finds contacts and users from two characters, grouped by type. Selecting a result opens its page: /contacts/<id> or /admin/users/<id>.

  • The records come from one procedure, search.records, which returns { type, label, items: [{ id, title, subtitle, href }] }[]. SEARCHABLE_TYPES in packages/api/src/search.ts is the one list of what can be found: an entry declares its canSearch check, its find query and the link of an item, so a new record type is one entry and the palette needs no change.
  • A role finds a type exactly when it can list it. Contacts need contact.read in the permission list of the caller (the check of permissionProcedure('contact', 'read'), which contact.list goes through) and users need the admin role (the check of adminProcedure, behind user.list). A type the caller may not read runs no query and returns no group, so the palette reveals nothing the tables would refuse.
  • The text is matched as plain text and whatever the case: % and _ match themselves. containsText uses the substring function of your database, never LIKE, so the match is the same on each. It scans the table, which is accepted at this size; add an index or a full-text search when a table grows.
  • Each type returns at most five items, newest contacts first and users by name. The palette waits for a pause in typing, drops the answer for an older text, and tells apart a search that is running, one that found nothing and one that failed (with a way to try again).

Profile with View Transitions

Route-based profile tabs using React 19 ViewTransition API with directional slide animations. Four sections:

  • Account — user info (email, role, joined date), edit display name, and change email: the form asks for the new address and the current password, the new address gets a link, and the address changes once the link is opened in a browser signed in to the account (the old address is told). There is no mailer: the link is logged by deliverLink in packages/auth/src/link-delivery.ts, the one place to plug a mail provider into. Works while public sign-up is closed
  • Security — change password (revokes other sessions)
  • Sessions — list active sessions with device/IP info, revoke individual or all others
  • Preferences — theme switcher (light/dark/system)

QueryBoundary

Reusable component wrapping Suspense + ErrorBoundary + QueryErrorResetBoundary. Used throughout for tRPC prefetch error handling with retry UI.

Local setup

scripts/local-setup.ts is a one-command bootstrap. It copies every .env.example to .env, starts the database with docker compose up -d --wait, applies the schema, then seeds demo data:

bun run local-setup

Each step is labelled and the script exits on the first failure.

Database seed

scripts/seed.ts is idempotent (safe to re-run) and flag-driven via node:util parseArgs:

FlagEffect
--fixturesAdd demo data (extra users, posts, contacts) generated with faker
--resetWipe existing data before seeding
--forceAllow --reset against a non-local database
--helpShow usage

Core seeding always creates three accounts via Better Auth's admin API:

  • admin@example.com / password (role: admin)
  • user@example.com / password (role: user)
  • manager@example.com / password (role: manager, read-only)

The seed runs from the repo root, so db:seed loads apps/web/.env via --env-file to resolve DATABASE_URL and BETTER_AUTH_SECRET. A --reset against a non-local DATABASE_URL is refused unless --force is passed.

Warning: These credentials are for local development only. Change passwords or disable seed accounts before deploying to any shared environment.

Extra dependencies

The packages below are declared on the web app; the batch app receives none of them.

PackagePurpose
lucide-reactIcons in navigation, forms, session list
react-error-boundaryQueryBoundary error handling
sonnerToast notifications
zodForm validation schemas
vaulDrawer behind the responsive dialog (mobile)
cmdkCommand palette (packages/ui)
@faker-js/fakerDemo data for the seed fixtures (dev only)

Environment variables

  • SEED_PASSWORD - Password of the seeded accounts, password by default (scope: app, read by db:seed)

Root scripts

ScriptCommandPurpose
local-setupbun scripts/local-setup.ts (tsx under npm and pnpm)One-command local bootstrap (env, docker, schema, seed)
db:pushcd packages/db && bun run db:pushPush schema to database
db:generateturbo db:generateGenerate migration files
db:migrateturbo db:migrateApply migrations
db:studioturbo db:studioOpen Drizzle Studio
db:seedbun --env-file=apps/web/.env scripts/seed.ts (tsx under npm and pnpm)Seed core data (--fixtures for demo data)
startturbo startStart production server

CLI usage

bunx create-faster myproject \
  --blueprint org-dashboard-nextjs \
  --linter biome \
  --git \
  --pm bun

Agent context

This blueprint ships AGENTS.md + docs/agents/ guides (architecture, auth & permissions, data layer) so AI coding agents understand the project out of the box. See Agent Context.

On this page