Cloudflare Fullstack
Auth + RBAC dashboard with a documents CRUD on D1, R2 uploads, and a cron Worker — all on Cloudflare.
Presentation
A complete Cloudflare-native SaaS starter: a Next.js (OpenNext) web app and a Hono cron Worker in a Turborepo, sharing one D1 database and one R2 bucket. It ships email/password auth with role-based access control (admin / manager / user, with the permissions of each role stored in D1), a documents domain with tRPC CRUD and direct-binding R2 file uploads, and a scheduled Worker that purges expired documents. Everything runs on Cloudflare's edge with no always-on server and no connection-string database.
Composition
Apps:
web— Next.js (→ docs) + shadcn/ui (→ module), next-themes (→ module), Better Auth (→ module), tRPC (→ module), TanStack Query (→ module), TanStack Form (→ module)cron— Hono (→ docs) scheduled Worker
Project addons:
- Database: → Cloudflare D1
- ORM: → Drizzle
- Deployment: → Cloudflare
Architecture
Two apps and three shared packages. Blueprint-specific files only:
apps/
├── web/ # Next.js (OpenNext) app
│ ├── wrangler.jsonc # DB + STORAGE (R2) bindings, OpenNext worker
│ └── src/
│ ├── app/
│ │ ├── layout.tsx # Root layout: AppProviders + sonner Toaster
│ │ ├── (auth)/
│ │ │ ├── layout.tsx # Redirects signed-in users to /
│ │ │ ├── login/{page,login-form}.tsx
│ │ │ ├── signup/{page,signup-form}.tsx
│ │ │ ├── forgot-password/{page,forgot-password-form}.tsx
│ │ │ └── reset-password/{page,reset-password-form}.tsx
│ │ ├── (dashboard)/
│ │ │ ├── layout.tsx # Session gate (getAuth) + sidebar shell
│ │ │ ├── page.tsx # Documents list (paged) + upload (permission-gated)
│ │ │ ├── profile/ # Tabbed (vertical): account, security, sessions, preferences
│ │ │ │ ├── layout.tsx # Vertical tab nav
│ │ │ │ ├── account/page.tsx # Avatar (R2) + inline-edit display name
│ │ │ │ ├── security/page.tsx # Change password
│ │ │ │ ├── sessions/page.tsx # Active sessions + revoke
│ │ │ │ └── preferences/page.tsx # Theme
│ │ │ └── admin/
│ │ │ ├── layout.tsx # Admin-only server gate
│ │ │ ├── users/page.tsx # Server page (title), renders users.client.tsx: paged datatable + create dialog
│ │ │ ├── users/[id]/page.tsx # Server page (title), renders user.client.tsx: per-user editor (inline edit, role, password, ban)
│ │ │ └── roles/ # Roles: page.tsx (server guard + prefetch) renders roles.client.tsx
│ │ └── api/
│ │ ├── documents/upload/route.ts # Multipart → R2 STORAGE.put
│ │ └── avatar/{route,[userId]/route}.ts # Avatar upload + serve from R2
│ ├── components/
│ │ ├── navigation/ # app-sidebar, app-header, nav-user, sidebar-links, command-palette
│ │ ├── admin/ # user-table, create-user-dialog, edit-user, generated-password, role-matrix, create-role-dialog
│ │ ├── profile/ # avatar-upload, account/security forms, session-list, tab-nav
│ │ ├── shared/data-table-shell.tsx # shuip datatable wrapper (search + sort, client or server mode)
│ │ ├── table-pagination.tsx # PagedList: empty state, page past the end, or rows with the pager
│ │ └── can.tsx # <Can> permission gate
│ ├── hooks/ # use-permission, use-page-params, use-user-list-params (the URL as the page)
│ └── lib/{constants,env}.ts # ROUTES (sidebar) + getEnv() bindings
└── cron/ # Hono scheduled Worker
├── wrangler.jsonc # crons trigger + DB + STORAGE bindings
└── src/index.ts # scheduled() → purge expired documents
packages/
├── ui/src/components/ # shuip data-table block, search-input, inline-edit + base shadcn (registry)
├── db/src/schema.ts # D1/sqlite schema: auth tables + documents + roles and role_permissions
├── auth/src/
│ ├── auth.ts # createAuth(db, cookiePlugin?) factory + admin plugin
│ ├── permissions.ts # the vocabulary: account statement, business statement, compiled admin role
│ ├── role-permissions.ts # hasPermission / permissionsOf: what a role may do, read from D1 per request
│ ├── role-assignment.ts # assign a role, ban or remove an account, and keep an administrator (the write is in role-store.ts)
│ ├── role-management.ts # create a role, grant or revoke a permission, delete a role nobody holds: the rules of the Roles page
│ ├── guard-administrators.ts # plugin in front of the admin endpoints that write a role, a ban or a removal
│ ├── role-store.ts # the writes of the role rules for D1: one conditional statement each, and the SQL of the default roles
│ ├── default-roles.ts # the default roles and their validation
│ ├── link-delivery.ts # link logger (reset, email change), the seam for a mailer
│ └── auth-client.ts # authClient with adminClient
└── api/src/
├── root.ts # tRPC root router
├── pagination.ts # page and page size rules, shared by the routers and the web app
├── user-list.ts # search and sort of the users table
├── page-query.ts # ordered page of a query (server only)
├── router/documents.ts # documents list/count/delete
├── router/users.ts # admin user list/count + CRUD (create/update/role/password/ban)
├── router/roles.ts # roles.matrix/create/setPermission/remove, admin only
├── router/permissions.ts # permissions.mine: the permission list of the caller
└── middleware/rbac.ts # permissionProcedure / adminProcedure
scripts/seed.ts # Local-D1 seed (users + demo documents, three pages of each)
scripts/default-roles.ts # db:roles / db:roles:remote: writes the default roles into an empty database
docs/agents/{auth-rbac,data-layer,storage,cloudflare-deploy}.mdThe structural d1 seam (apps/web/src/lib/server.ts with getDb()/getAuth()), next.config.ts, and the base OpenNext deploy scripts come from the Next.js stack and the Cloudflare deployment — they are not blueprint files.
What's included
D1 per-request, never a singleton
D1 is only reachable through a request- or event-bound binding, so the blueprint never imports a module-level db or auth. The web app builds them per request via getDb()/getAuth() (from @/lib/server), tRPC procedures use ctx.db, and the cron Worker calls createDb(env.DB) inside scheduled(). See Data layer and the generated docs/agents/data-layer.md.
Auth & RBAC
Better Auth with the admin plugin for account administration, and roles whose permissions are data. packages/auth/src/permissions.ts holds the vocabulary: the account resources of the plugin (user, session, held by admin alone, compiled and never stored) and the business resources (document today), the only names a role can be given. What each role may do on them is read from the roles and role_permissions tables of D1 on every request, by one function, read once per request and never kept after it: a permission removed from the table is refused on the next request, a role the database does not know holds nothing, and a stored row that names user or session grants nothing. admin has no rows and keeps every business action. Server endpoints are gated with permissionProcedure('document', action) (typed from the vocabulary) / adminProcedure; the UI gates with <Can permissions={...}> backed by a three-state verdict (unknown, granted, denied) over the permission list of the caller, which the dashboard layout fetches on the server so the first render of the sidebar and the buttons is already right. The tables start empty because no template ships a migration: local-setup and the deploy steps run db:roles / db:roles:remote, a command that writes the default roles (user: its own documents CRUD, manager: read every user's documents) only into a database that has no role, so a role you deleted or a permission you revoked is never written back. The admin Roles page (/admin/roles) renders the role × permission matrix from the database and edits it at runtime: an administrator ticks a box to grant a permission or clears it to revoke one (it applies to the next request of everyone holding the role), creates a role, and deletes a role nobody holds, after a confirmation. Only the literal admin role can do this; admin itself cannot be edited or deleted, admin and user are reserved identifiers, an identifier is lowercase letters, digits and hyphens and cannot be renamed, and a grant must name a permission of businessStatement. A role someone holds is refused in the delete statement itself, so an assignment and a delete at the same moment cannot leave an account on a deleted role. Password reset is wired too: sendResetPassword hands the link to deliverLink in packages/auth/src/link-delivery.ts. There is no mailer, so it logs the link to the server console in development and in production, and in production also logs a warning, No mailer is configured: the link is only in the Worker logs. Plug a mail provider (Resend, SES, Postmark, ...) into that function before going live. It sits behind /forgot-password and /reset-password pages. Changing the email address from the profile uses the same function: the form asks for the new address and the current password (so a stolen session cannot point the account at someone else's address), the new address gets a link, and the address changes only once the link is opened in a browser signed in to the account. The old address is told once it changed. Details in the generated docs/agents/auth-rbac.md.
User management
The admin Users area is backed by a users tRPC router (all adminProcedure). /admin/users lists accounts in the shuip DataTableShell with a Create user dialog (see Paginated lists) — the server generates a random password and reveals it once. /admin/users/[id] is a per-user editor where the display name, first/last name and phone are inline-edit fields, alongside role, password reset, ban/unban and delete. The role select lists admin and the roles of the database, so a role you create is assignable at once. On your own account the role, ban and delete controls are not offered, and the server refuses them with a 400. A role is exactly one existing id: the Better Auth admin plugin reads user,admin as an administrator and accepts a list, so the guardAdministrators plugin refuses anything else on every path, and the last administrator can never be demoted, banned or removed (the check is part of the write, since D1 has no interactive transaction). Impersonation, setting a password and changing an email are equivalent to root for an admin and are documented as such. A Better Auth refusal inside a router reaches the toast as its own message (see tRPC). Credential- and session-touching actions go through the Better Auth admin API per-request (createAuth(ctx.db).api.* with the request headers); profile columns are written directly via Drizzle.
Dashboard shell
A collapsible shadcn sidebar (SidebarProvider + AppSidebar) drives navigation from a single ROUTES table (lib/constants.ts), permission-gated per item — a whole category label is hidden when none of its links are permitted (a granted verdict of the permission list). The footer user menu (nav-user) carries the avatar, theme toggle, and sign-out; the header renders breadcrumbs (so pages don't repeat their own title). A search field under the logo, or Ctrl+K (Cmd+K on macOS), opens a command palette that lists the pages the permission list grants, from the same ROUTES table and permission filter as the sidebar. The shadcn primitives the shell needs (sidebar, sheet, skeleton, dropdown-menu, breadcrumb, avatar, plus table, badge, dialog, popover, command, search-input) and the shuip data-table block live in packages/ui as registry-faithful code.
Forms
Every form is built on the shuip TanStack-Form field kit (useAppForm in packages/ui/src/lib/form.ts) and validates on submit. Creation and security forms use plain inputs (InputField, PasswordField, SelectField); single-value live edits use InlineEditField (the profile display name and the per-user editor commit on blur/enter).
Profile
A tabbed area (/profile) with a vertical tab rail, over authClient — no extra tRPC routers: account (avatar, inline-edit display name, email change by confirmation link), security (change password), sessions (list + revoke), preferences (theme). The avatar uploads to R2 via POST /api/avatar (avatars/<userId>), is served back through GET /api/avatar/[userId] (session-gated), and the returned URL is saved to user.image with authClient.updateUser.
Paginated lists
users.list and documents.list return one page, never the whole table, and users.count and documents.count return the total. The users table searches and sorts on the server too. Everything is in the URL, so a view can be bookmarked and the back and forward buttons walk through it: /admin/users?page=2&pageSize=25&search=ada&sort=-name (a value at its default is left out).
packages/api/src/pagination.tsvalidatespage(a whole number from 1 to 10,000) andpageSize(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.packages/api/src/user-list.tsadds the search (a substring of the name, the email or the role, in any case) and the sort (newest first, or by name or email in either direction). A sort the table does not offer is the default order, so a URL never picks a column.- Each sort is served by an index of the
userstable ((created_at, id),(name, id)and the unique email), and every order ends with a unique column so a user never appears on two pages or on none. A new sort needs its own index. The search scans the table. - The total is its own
countquery, keyed by the search alone: changing the page, the page size or the sort does not count again, and a mutation that adds or removes a row invalidates it. PagedList(src/components/table-pagination.tsx) renders the empty state, a page past the end with a button to the last page, or the rows with a pager. The users table and the documents list use it.local-setupseeds 30 users and 24 documents, three pages of each.
Documents CRUD + R2 uploads
The dashboard lists documents one page at a time (own rows for users; all rows for admin/manager) and uploads files. Upload is a Route Handler (api/documents/upload) that authenticates, caps the file at 25 MB (Worker memory), STORAGE.puts it under documents/<userId>/<id>, and inserts the row. Deletion (tRPC documents.delete) removes the R2 object and the row together. See docs/agents/storage.md.
Cron Worker
apps/cron is a Hono Worker whose scheduled() handler (daily at 03:00 UTC) deletes documents whose expiresAt has passed — both the R2 object and the D1 row. dev runs it under wrangler dev on port 3001, with the same local D1 and R2 state as the web app. While dev runs, fire it locally with curl -X POST "http://localhost:3001/cdn-cgi/local/explorer/api/local/scheduled?worker=<project>-cron" -H 'Content-Type: application/json' -d '{"cron":"0 3 * * *"}'.
Local seed
scripts/seed.ts opens the local miniflare D1 sqlite directly (@libsql/client, so it runs under Node and Bun) and creates admin@example.com, manager@example.com, and user@example.com (password password), plus, with --fixtures, 27 more demo users and 24 demo documents — a third pre-expired to exercise the cron purge. It runs automatically as part of local-setup.
Local setup & deploy
bun install
bun run local-setup # .env files, reset + migrate local D1, default roles, generate CF types, seed
cd apps/web && bun run preview # OpenNext preview against local bindingsProvisioning the live D1 database + R2 bucket, pasting the database_id into both wrangler.jsonc files, learning the production URL (https://<project>-web.<subdomain>.workers.dev) before the first build, setting secrets, deploying both Workers and promoting the first admin are documented in the generated docs/agents/cloudflare-deploy.md.
Sign-up is open and every account gets the user role, and the seed only writes the local database, so the first admin of a deployed app is promoted by hand: sign up, then run wrangler d1 execute DB --remote --command "UPDATE users SET role = 'admin' WHERE email = lower('<your email>')" from apps/web (with the bunx, npx or pnpm exec of your package manager). The generated README carries the same steps, so they reach you under --no-agent-context too. The role is read on every request, so the session sees /admin as soon as the app reloads.
The web Worker lists BETTER_AUTH_SECRET and BETTER_AUTH_URL under secrets.required in its wrangler.jsonc (the cron Worker has none), so its deploy fails until both are set. Because build:cf bundles every .env* value into the Worker, build the one you deploy where apps/web/.env holds no real secret, with NEXT_PUBLIC_APP_URL exported in the shell as the production URL, and set production secrets with wrangler secret put (a new Worker takes them from a gitignored file on its first deploy: deploy -- --secrets-file .prod.env). The generated docs/agents/cloudflare-deploy.md has the details. See Cloudflare for the deployment details.
Extra dependencies
lucide-react, sonner and zod are declared on the web app only; the cron Worker receives none of them.
| Package | Purpose |
|---|---|
lucide-react | Icons (upload, delete, nav) |
sonner | Toast notifications |
react-error-boundary | Error boundaries |
zod | Input validation (tRPC, forms) |
@faker-js/faker | Seed data (dev) |
vaul | Drawer primitive (UI package) |
@tanstack/react-table | Users datatable (UI package) |
@dnd-kit/core, @dnd-kit/sortable, @dnd-kit/utilities | Datatable row drag-reorder (UI package) |
cmdk | Command palette and datatable filters (UI package) |
Environment variables
| Variable | Description |
|---|---|
NEXT_PUBLIC_APP_URL | Public web app URL (scope: app) |
SEED_PASSWORD | Password of the seeded accounts, password by default (scope: root, in .env.seed at the repo root, read by db:seed next to apps/web/.env). It has a file of its own because build:cf bundles every .env* of apps/web and of the repo root into the web Worker |
There is no database connection string — D1 is the DB binding only.
CLI usage
bunx create-faster my-app \
--blueprint cloudflare-fullstack-nextjs \
--linter biome \
--git \
--pm bunAgent context
This blueprint ships AGENTS.md + docs/agents/ guides (auth & RBAC, data layer, storage, Cloudflare deploy) so AI coding agents understand the project out of the box. See Agent Context.

