Create FasterCreate Faster
Business

Multitenant SaaS

B2B SaaS dashboard with organizations, custom RBAC, and link-based invitations. Ships as a turborepo with a Next.js web app, a Node batch worker, and shared packages.

Presentation

A production-ready B2B SaaS starter. You get a Next.js dashboard with email/password authentication (sign-up, sign-in, forgot/reset password), Better Auth's organization plugin for multi-tenancy, a custom RBAC system with runtime role creation, link-based invitations (no email provider required), full projects CRUD scoped per organization, an account/security/sessions/preferences profile area, and a Node batch worker for background jobs. Ships as a turborepo with shared auth, db, api, and ui packages, a one-command local setup, and an idempotent, faker-powered seed.

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)/
│   │   ├── login/
│   │   │   ├── page.tsx
│   │   │   └── login-form.tsx                        # Email/password sign-in
│   │   ├── signup/
│   │   │   ├── page.tsx
│   │   │   └── signup-form.tsx                       # Email/password sign-up (honors ?redirect)
│   │   ├── forgot-password/
│   │   │   ├── page.tsx
│   │   │   └── forgot-password-form.tsx              # Request reset link
│   │   ├── reset-password/
│   │   │   ├── page.tsx                              # Reads ?token / ?error
│   │   │   └── reset-password-form.tsx               # New-password form
│   │   └── accept-invitation/[id]/
│   │       ├── page.tsx                              # Accept invitation landing page
│   │       └── accept-button.tsx                     # Client action to accept invite
│   ├── (onboarding)/
│   │   └── onboarding/page.tsx                       # Create first organization
│   └── (dashboard)/
│       ├── layout.tsx                                # Sidebar + auth guard + active org check
│       ├── page.tsx                                  # Dashboard home (project / member counters)
│       ├── projects/
│       │   ├── page.tsx                              # Project list
│       │   └── [id]/
│       │       ├── page.tsx                          # Project detail (server-side prefetch)
│       │       └── project.client.tsx                # Client view + edit dialog
│       ├── settings/
│       │   ├── general/page.tsx                      # Org name + danger zone (delete org)
│       │   ├── members/page.tsx                      # Member list + pending invitations
│       │   └── roles/page.tsx                        # Role list + permissions grid
│       └── 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/
│   ├── members/                                      # Members table, invite dialog, invitation link dialog, pending invitations table
│   ├── navigation/                                   # App sidebar, header with breadcrumb, org switcher, nav-user dropdown, sidebar links, command palette
│   ├── profile/                                      # Account form, security form, session list, preferences, tab nav
│   ├── projects/                                     # Project table, create/edit/delete dialogs, project form
│   ├── roles/                                        # Roles table, permissions grid, role form dialog
│   ├── can.tsx                                       # Permission gate component (<Can permissions={{ resource: ['action'] }}>)
│   ├── confirm-dialog.tsx                            # Confirmation dialog for removing a member or deleting a role
│   └── query-boundary.tsx                            # Suspense + ErrorBoundary + QueryErrorResetBoundary
├── hooks/
│   └── use-permission.ts                             # usePermission({ resource: ['action'] }) → { allowed, loading }
├── lib/
│   ├── auth/
│   │   └── session.ts                                # requireSession(): cached session check, redirects to /login or /onboarding
│   ├── allowed-routes.ts                             # useAllowedRoutes(): the pages the active organization lets the user open (sidebar and palette)
│   └── constants.ts                                  # ROUTES with per-route { resource, action } permission gating, PROFILE_TABS
└── proxy.ts                                          # Next.js middleware (proxy export): session cookie guard

Auth package (packages/auth)

src/
├── auth.ts               # Better Auth config (organization plugin, drizzle adapter)
├── auth-client.ts        # Client with organizationClient + inferAdditionalFields
├── link-delivery.ts      # deliverLink(): logs reset and invitation links, the seam for a mailer
├── organization-guard.ts # Plugin in front of the organization endpoints: who may give a role, role names, invitation visibility
├── permissions.ts        # RBAC catalog: 5 resources × 15 actions, 3 built-in roles
├── role-grants.ts        # Which roles a member may give, which invitations it may see
└── types.ts              # Session type via auth.$Infer.Session

API package (packages/api)

src/
├── root.ts             # appRouter composition (project, organization, member, role, invitation, session, user, search)
├── search.ts           # SEARCHABLE_TYPES: the projects and members of the active organization 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         # orgProcedure, hasPermission, permissionProcedure(resource, action), assertInScope
└── router/
    ├── project.ts      # Project CRUD scoped to active org
    ├── organization.ts # Update / delete org + active membership
    ├── member.ts       # List members, assignableRoles, change role, remove
    ├── role.ts         # Catalog + dynamic role CRUD via Better Auth org-roles API
    ├── invitation.ts   # Create, list, cancel invitations
    ├── session.ts      # List + revoke sessions
    ├── user.ts         # Profile read + update
    └── search.ts       # records: the groups of records the palette shows

What's included

Authentication flows

Email/password auth backed by Better Auth, with all four standard flows pre-wired:

  • Sign-in (/login) — honors ?redirect=… and pushes the user to the requested page after login. A user who is already signed in is redirected to / instead of seeing the form.
  • Sign-up (/signup) — same ?redirect behavior, creates the user via authClient.signUp.email.
  • Forgot password (/forgot-password) — calls authClient.requestPasswordReset and shows a success state without leaking whether the email exists.
  • Reset password (/reset-password?token=…) — reads the token from search params, calls authClient.resetPassword, and routes errors via ?error=….

Reset and invitation links have no mailer. sendResetPassword and the organization plugin's sendInvitationEmail (both in packages/auth/src/auth.ts) hand the link to deliverLink in packages/auth/src/link-delivery.ts, which logs it to the server console ([reset-password] <email> → <url>, [invitation] <email> → <url>), in development and in production. In production it also logs a warning, No mailer is configured: the link is only in the server logs, so a user who forgot a password cannot reset it from their inbox. An invitation link is also shown in the invite dialog, ready to copy. The email change link and the notice to the old address leave through the same function. Before going live, plug a mail provider (Resend, SES, Postmark, ...) into deliverLink, the one place every link leaves the server.

src/proxy.ts exposes a single proxy export (Next.js middleware) that allow-lists /login, /signup, /forgot-password, /reset-password and /accept-invitation, and redirects every other page without a session cookie to /login (preserving the original path and query as ?redirect). It runs no database query and does not match /api routes, so an anonymous tRPC call gets a 401 from the procedure. The cookie check is optimistic: the dashboard layout validates the session through requireSession() (src/lib/auth/session.ts) and sends users without an active organization to /onboarding. Pages that prefetch tRPC data call it before the prefetch, because a layout and its page render in parallel and a forged or expired cookie must redirect without a failed query.

Multi-tenant organizations

Organizations are first-class entities powered by Better Auth's organization plugin. Each user belongs to one or more organizations with their own members, roles, and projects. After sign-in, unauthenticated users and users with no active organization are redirected to /onboarding, which lists the organizations the user already belongs to (the session can lose its active organization) next to the form that creates a new one. The dashboard layout reads the active organization from the session and gates all API calls to it.

Custom RBAC

The permission system is defined in packages/auth/src/permissions.ts using Better Auth's createAccessControl with dynamicAccessControl enabled to support runtime role creation:

Resources and actions:

ResourceActions
organizationupdate, delete
membercreate, update, delete
invitationcreate, cancel
accreate, read, update, delete
projectcreate, read, update, delete

The statement and the owner and admin grants start from the ones Better Auth's organization plugin ships (without team, which is not enabled) and add project, so every action name is one Better Auth checks on its own endpoints (removeMember needs member.delete, createInvitation needs invitation.create). permissionProcedure, usePermission and <Can> are typed on the statement, so an action it does not declare fails to compile.

The role-management resource is named ac (access control), not role — Better Auth's dynamic-access-control endpoints (createOrgRole, updateOrgRole, deleteOrgRole) require this internal name when checking permissions on custom org roles.

Built-in roles (immutable defaults):

RolePermissions
ownerFull access to all resources
adminAll member, invitation, role (ac), project actions; cannot delete the organization
memberRead-only project access

Admins can create additional roles with custom permission combinations via the Roles UI. Custom roles are stored in the database and resolved dynamically at runtime.

A member whose role holds member.update, member.delete, invitation.create, ac.update or ac.delete acts only on the roles, members and invitations whose permissions it holds. packages/auth/src/organization-guard.ts enforces it, with the following in front of the organization endpoints, for the tRPC procedures and for a direct request to /api/auth/organization/* alike:

  • A role is given to a member or an invitation as one id, and only by a member that holds every permission of that role. The members table and the invite dialog offer those roles and no others.
  • A member is changed or removed only by a member that holds every permission of the role it has now, and a stored role is changed or deleted only by a member that holds every permission of it. A role that a pending invitation carries is not deleted until the invitation is cancelled or expires.
  • A role name is one id of lowercase letters, digits and hyphens, at most 40 characters. The role form shows the error as you type.
  • A role is not renamed, because members and invitations store it by name. Create the new role, move the members, delete the old one.
  • Invitation ids are shown only to the members who could have sent the invitation, and a pending invitation is replaced or sent again only by one of them. The id is what its recipient joins with, so it stays with the members who may send the invitation.

The <Can> component and usePermission hook provide declarative permission checks in the UI:

<Can permissions={{ project: ['create'] }}>
  <CreateProjectButton />
</Can>
const { allowed, loading } = usePermission({ project: ['create'] });

Both ask the endpoint the server's permissionProcedure asks, and the write actions of the dashboard (new project, edit and delete project, save and delete organization, invite, change role, remove member, cancel invitation, create, edit and delete role) render only for a role that holds the permission. A page read that is refused shows its error at once: the query client does not retry a 4xx answer in the browser. Removing a member or deleting a role asks for confirmation in the app's dialog.

On the server, tRPC enforces the same model through two composable procedures in packages/api/src/middleware/rbac.ts:

  • orgProcedure — requires session.activeOrganizationId and injects ctx.orgId.
  • permissionProcedure(resource, action) — extends orgProcedure and calls auth.api.hasPermission so custom roles resolve at runtime.
  • assertInScope(row, ctx) — narrows a row's organizationId against ctx.orgId and throws NOT_FOUND on mismatch, preventing cross-org data leaks in router handlers.

No email sending is required. An admin creates an invitation in the Members settings page, copies the generated link, and shares it manually (Slack, email, etc.). The recipient opens /accept-invitation/[id] to join the organization. Pending invitations are listed in a separate table with the option to copy or revoke them.

Org switcher

The sidebar includes an org switcher component that lists all organizations the user belongs to. Switching orgs updates the active organization in the session without a full page reload.

Command palette

A search field under the org switcher in the sidebar, or Ctrl+K (Cmd+K on macOS), opens a command palette. It lists the pages the active organization lets you open, from the same ROUTES table and the same permission answers as the sidebar, and finds the projects and the members of the active organization from two characters, grouped by type. Selecting a result opens its page: /projects/<id>, or /settings/members for a member, who has no page of their own.

  • 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.
  • Results come from the active organization of your session only, read on the server, and every query is scoped to it. Switching organization changes what the palette finds.
  • A role finds a type exactly when it can list it. Projects need project: ['read'] (the check of permissionProcedure('project', 'read'), which project.list goes through), a custom role included. Members are listed to any member of the organization (member.list asks no permission), so any member finds them. A type the caller may not read runs no query and returns no group.
  • The text is matched as plain text and whatever the case: % and _ match themselves. It scans the organization's rows, 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.

Projects CRUD

Full create, read, update, delete for projects scoped to the active organization. Project form with Zod validation via TanStack Form. Project table with inline actions gated by the project:update and project:delete permissions.

Settings pages

Three settings pages under /settings:

  • General — rename the organization; danger zone with delete organization (owner only)
  • Members — member list with role assignment; pending invitations table with copy-link and revoke actions
  • Roles — role list with a permission grid for creating and editing custom roles (admin and owner)

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)
  • 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 members, projects, pending invitations) generated with faker
--resetWipe existing data before seeding
--forceAllow --reset against a non-local database
--helpShow usage

Core seeding always provisions, via Better Auth's API and direct Drizzle inserts:

  • Users — owner@example.com and member@example.com, both with password password
  • Organization — Acme Inc. (slug acme) with the owner as owner and the second user as member

With --fixtures, faker adds four extra members, six projects, and three pending invitations scoped to the organization (deterministic via a fixed seed).

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.

What's intentionally excluded

FeatureNotes
Email sendingInvitations use copy-paste links; no SMTP or transactional email provider
Billing / subscriptionsNo Stripe or payment integration
Audit logMember and permission changes are not logged
Sub-organizations / teamsOne organization level only; no nested team hierarchy
WebhooksNo outbound event notifications

Extra dependencies

App (apps/web) and root extras declared by the blueprint:

PackagePurpose
@hugeicons/reactIcon library used throughout the dashboard
@hugeicons/core-free-iconsIcon set for @hugeicons/react
lucide-reactInline icons for navigation and dialogs
react-error-boundaryQueryBoundary error handling
sonnerToast notifications
zodForm validation schemas
cmdkCommand palette (packages/ui)
@faker-js/fakerDemo data for the seed fixtures (dev only)

Shared UI package (packages/ui) extras:

PackagePurpose
@tanstack/react-formBacks the shuip tanstack-form field components shipped in packages/ui/src/components/ui/shuip/tanstack-form/*

Environment variables

Extra env vars declared by the blueprint (on top of those provided by better-auth, drizzle, and postgres):

VariableScopePurpose
NEXT_PUBLIC_APP_URLapps/web/.env.examplePublic origin used for invitation links and password-reset redirects

Root scripts

ScriptCommandPurpose
local-setupbun scripts/local-setup.ts (tsx under npm and pnpm)One-command local bootstrap (env, docker, schema, seed)
db:pushturbo 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 multitenant-saas-nextjs \
  --linter biome \
  --git \
  --pm bun

Getting started

After generating the project:

# Install dependencies
bun install

# Copy env files, start the database, apply the schema, and seed demo data
bun run local-setup

# Start the dev server
bun run dev

Login with owner@example.com / password to explore the full feature set, or member@example.com / password for a restricted view.

Agent context

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

On this page