This project is opinionated towards Bun and renders on the server with TanStack Start and Nitro.
- Framework: TanStack Start — full-stack React with TanStack Router, server functions, and SSR.
- Server: Nitro — handles server-side logic and deployment presets.
- ORM & Database: Drizzle ORM with Bun's native SQL driver (
bun:sql/drizzle-orm/bun-sql). - Auth: Better Auth — email + password, email OTP, passkeys, and optional Google OAuth. Rate limited at the Better Auth layer (20 req/60 s).
- Theme: next-themes — class-based theme management on
htmlwith a mounted client toggle.
.
├── docs/
│ ├── ADDING-A-FEATURE.md # The schema-to-tests sequence for a new feature
│ ├── ARCHITECTURE.md # This file
│ ├── CHANGELOG.md # Release history
│ ├── CONTRIBUTING.md # Branch, commit, and test conventions
│ ├── DEPLOYMENT.md # Hosting options and platform config
│ ├── DESIGN.md # Visual system notes
│ └── DEVELOPMENT.md # Local setup, scripts, database, and testing guide
├── AGENTS.md # Developer guide for agents
├── src/
│ ├── components/
│ │ ├── layout/ # Header and shell layout
│ │ ├── pages/ # Route-level page compositions
│ │ ├── providers/ # Client providers (theme)
│ │ └── ui/ # Reusable UI primitives
│ ├── db/ # Drizzle schema, client, and migrations
│ │ ├── drizzle/ # Generated SQL migrations (drizzle-kit)
│ │ ├── schema.ts # notes table (with userId FK)
│ │ └── auth-schema.ts# Better Auth tables
│ ├── features/
│ │ ├── auth/ # Session/account server fns, query options, login/signup/OTP/reset forms
│ │ ├── emails/ # Email templates
│ │ ├── notes/ # Notes schema, server functions, and records.server
│ │ └── uploads/ # Upload schema, server function, and presign.server
│ ├── lib/ # Shared integrations and utilities
│ │ ├── auth-client.ts # Better Auth React client
│ │ ├── auth.server.ts # Better Auth server config
│ │ ├── logger.ts # LogTape app logger and sink config
│ │ ├── mailer.server.ts # Resend email sender (lazy init, optional)
│ │ ├── redis.server.ts # Bun-native Redis client (optional)
│ │ ├── seo.ts # SEO metadata, OpenGraph, structured data, crawler formats
│ │ ├── storage.server.ts # Bun-native S3-compatible upload client (optional)
│ │ └── utils.ts
│ ├── routes/ # TanStack Router routes and API handlers
│ │ ├── __root.tsx # App shell
│ │ ├── _authenticated.tsx # Pathless layout route guarding authenticated pages
│ │ ├── _authenticated/
│ │ │ ├── dashboard.tsx # Protected route — notes CRUD, upload widget
│ │ │ └── settings.tsx # Protected route — profile, verification, password, providers, passkeys, delete account
│ │ ├── index.tsx # Landing page
│ │ ├── login.tsx # Auth route — redirects signed-in users
│ │ ├── signup.tsx # Auth route — redirects signed-in users
│ │ ├── verify-otp.tsx
│ │ ├── reset-password.tsx # Request a reset link, or set a new password with ?token=
│ │ ├── sentry-example.tsx # Dev only
│ │ ├── robots[.]txt.ts # Plain text crawler directives
│ │ ├── sitemap[.]xml.ts # XML sitemap
│ │ └── api/
│ │ ├── auth/$.ts # Better Auth handler
│ │ ├── health.ts
│ │ └── sentry-example.ts # Dev only
│ └── globals.css # Global styles (Tailwind CSS v4)
├── tests/ # Vitest and Playwright suites
├── instrument.server.mjs # Server bootstrap — Sentry init and logging
├── components.json # shadcn/ui configuration
├── Dockerfile
├── drizzle.config.ts
└── package.json
- Routing: Managed by TanStack Router.
src/routes/__root.tsxcomposes the shell, theme provider, header, and page outlet. - SSR: TanStack Start handles the initial HTML render on the server via Nitro. The request middleware in
src/start.tsadds baseline security headers to every response it handles —X-Content-Type-Options,Referrer-Policy,X-Frame-Optionswithframe-ancestors 'none',Cross-Origin-Opener-Policy, and HSTS in production builds. There is no script-sourceContent-Security-Policyyet; adding one means putting a nonce on the inline scripts TanStack Start and next-themes emit. - Protected routes:
src/routes/__root.tsxresolves the session once per navigation and puts{ user }on the route context, which the header uses to render the signed-in nav on the server. The pathless_authenticated.tsxlayout only refuses an unauthenticated visitor with a redirect to/loginand re-emits the narrowed user for child routes (dashboard.tsx,settings.tsx). Auth routes (/login,/signup) redirect signed-in arrivals to/dashboard. - Server functions:
src/features/notes/server-fns.tsexposeslistNotes,createNote, anddeleteNote, andsrc/features/uploads/server-fns.tsexposescreateUploadUrl, all viacreateServerFn. Every function runs behind the middleware insrc/features/auth/session.ts, which resolves the session. A refusal is a thrownError, the behaviour TanStack Start documents: the caller catches it and readsmessage. The middleware's catch callssetResponseStatusfirst, so a direct HTTP caller still sees the status: 400 when the payload misses the schema, 401 without a session, 404 when the row is missing, 422 when the payload parses but the server refuses it, and 503 when a dependency is unconfigured. - Query cache:
src/router.tsxcreates one TanStack QueryQueryClientper router (30s defaultstaleTime) andsetupRouterSsrQueryIntegrationsupplies the provider plus SSR dehydration/hydration. Route loaders prefetch with the samequeryOptionsobjects their components read (accountOptionsinsrc/features/auth/accounts.ts); mutations over loader-owned data callrouter.invalidate(). - Auth flow: Forms in
src/features/auth/components/*callsrc/lib/auth-client.ts./loginsupports email + password, email OTP, passkeys, and Google OAuth (when configured)./signupcreates a password account (then holds the user on a "check your email" prompt) or sends an OTP;/verify-otpconfirms the code and offers passkey enrollment;/reset-passwordboth requests a reset link and consumes it (?token=). - File uploads:
createUploadUrlinsrc/features/uploads/server-fns.tsvalidates the request throughsrc/features/uploads/schema.tsand reacheshandleCreateUploadUrlinpresign.server.tsthrough a dynamic import. It presigns auploads/<userId>/<uuid>.<ext>PUT URL and returns{ url, key }; the dashboard PUTs the file bytes straight to storage, so the server never proxies them. An unsupported content type or a file over 10 MB is a 422, and an unsetS3_ENDPOINTis a 503.
PostgreSQL is accessed using Drizzle ORM paired with Bun's native SQL driver (bun:sql via drizzle-orm/bun-sql).
- Schemas: Defined in
src/db/schema.ts(application tables such asnotes) andsrc/db/auth-schema.ts(Better Auth tables:user,session,account,verification,passkey). - Migrations Directory: Configured in
drizzle.config.tsto output migrations tosrc/db/drizzle/. - Generating Migrations: When schema files are updated, run
bun run db:generateto produce timestamped SQL migration files and update the snapshot journal insrc/db/drizzle/meta/. Never handwrite SQL migrations. - Applying Migrations: Run
bun run db:migrateto execute pending SQL migrations against the configured database (DATABASE_URL). For quick local development without migration tracking,bun run db:pushcan be used.
For developer commands, seeding, and local workflows, see the Development Guide.
Handled by Better Auth. Supported flows:
- Email + password — sign up and sign in with a password. The sign-up, reset-password, and settings change-password forms share
PasswordSchema(src/features/auth/schema/password.ts): 8–128 characters with uppercase and lowercase letters, a number, and a symbol. That policy is client-side; Better Auth itself only enforces its 8-character minimum, so add abeforehook on/sign-up/email,/reset-password, and/change-passwordif you need it enforced server-side too. Always available. Password hashes live in the existingaccount.passwordcolumn, so no migration is involved. Sign-ups are stored with an emptyname, matching what the email-OTP flow does, and are auto-signed-in (requireEmailVerificationis off, so an unverified user can still sign in). - Email verification —
emailVerification.sendOnSignUpmails a link via theVerificationEmailtemplate; Better Auth's own/api/auth/verify-emailendpoint consumes it, so there is no app route for it./signupshows a "check your email" prompt after a password sign-up rather than navigating away, because the window this closes is otherwise invisible: an email-OTP sign-in by an unverified user triggers Better Auth'srevokeUnprovenAccountAccess, which deletes every account row and session that user has (its defence against someone registering a password on an address they do not own) — so an unverified password would be discarded the first time that user signs in with a code. Verified users keep their password across an OTP sign-in. SetemailAndPassword.requireEmailVerification: trueif you would rather block sign-in until the link is clicked./settingsshows the currentemailVerifiedstate and, when unverified, re-sends the link with a/settingscallback. - Password reset —
/reset-passwordsends a link (1 hour expiry) viaResetPasswordEmail. Better Auth's callback bounces the emailed link off/api/auth/reset-password/:tokenand back to/reset-password?token=…, or?error=INVALID_TOKENwhen it has expired. Reset also creates a credential account when the user has none, so OTP-only and Google-only users can adopt a password this way. It does not create a session, andrevokeSessionsOnPasswordResetdrops every existing session, so the user signs in afterwards. While signed in,/settingscan change the password withchangePassword(current password required, other sessions revoked) and offers the same emailed reset link as the fallback when the user has no password or has forgotten it. - Email OTP — sign in and sign up via one-time code. Always available.
- Passkeys — register and authenticate with a device credential. Always available.
- Google OAuth — enabled only when
GOOGLE_CLIENT_IDandGOOGLE_CLIENT_SECRETare set. The app boots and functions without them. - Last login method — the
lastLoginMethodplugin stores the method inuser.last_login_method(storeInDatabase: true) and sets a non-httpOnly cookie./loginreads the cookie to show "Last sign-in used …"; the persisted field is also available assession.user.lastLoginMethod.
Rate limiting is configured at 20 requests per 60-second window using Better Auth's built-in rateLimit option.
Tailwind CSS v4 is integrated via @tailwindcss/vite. Theme switching is class-based on the html element through next-themes.
LogTape provides the app logger in src/lib/logger.ts. The server bootstrap (instrument.server.mjs) initialises Sentry. In development bun run dev preloads it with --import; in production builds the sentryTanstackStart Vite plugin bundles it into the Nitro server and runs it when the server starts, so bun run start and the Docker image need no preload. It configures:
dataCollection— user identifiers, cookies, request bodies, and database payloads are not forwarded.tracesSampleRate: 0.1— 10% of server traces are sampled to control cost.
Loosen dataCollection and raise tracesSampleRate only intentionally, after reviewing your data-handling obligations.