# Achromatic TanStack Start Drizzle starter kit ## Current product facts The following claims describe the current products and are generated from the site's shared product configuration. ### Current starter kits - [Pro Next.js + Prisma + Better Auth](https://www.achromatic.dev/docs/starter-kits/pro-nextjs-prisma) - [Pro Next.js + Drizzle + Better Auth](https://www.achromatic.dev/docs/starter-kits/pro-nextjs-drizzle) - [Pro TanStack Start + Prisma + Better Auth](https://www.achromatic.dev/docs/starter-kits/pro-tanstack-prisma) - [Pro TanStack Start + Drizzle + Better Auth](https://www.achromatic.dev/docs/starter-kits/pro-tanstack-drizzle) ### Included capabilities - Better Auth authentication with email and password, passkeys, Google OAuth and TOTP two-factor authentication - Stripe subscriptions, one-time payments, per-seat pricing, credits, paywalls and webhooks - Organizations, team invitations, roles and access control - PostgreSQL with either Prisma or Drizzle ORM - Components built with shadcn/ui and Tailwind CSS - Transactional email with Resend and React Email - AI integration with the Vercel AI SDK ### License and access - Price: 180 USD, paid once - The purchase includes four current starter kits and future updates made available under the license - The license covers unlimited projects for one licensed individual, team or organization - Repository invitations are sent to the GitHub username supplied at checkout - Expired invitations, restoration requests and teammate access are handled through [support](https://www.achromatic.dev/contact) # TanStack Start Drizzle documentation ## Architecture **URL**: https://www.achromatic.dev/docs/starter-kits/pro-tanstack-drizzle/architecture **Description**: Understand routes, server functions and shared application code. `src/routes` contains TanStack Router's file routes. `src/routes/__root.tsx` defines the document shell, metadata and global error handling. Marketing, authentication, dashboard and API routes live in the same route tree. `src/router.tsx` creates the router and `vite.config.ts` configures the TanStack Start, Content Collections, Tailwind and Nitro plugins. Route guards run in `beforeLoad`: `src/routes/dashboard.tsx` loads the session, while organization and admin routes check membership or platform role. A `beforeLoad` guard can also run during client-side navigation, so it is **not** an authorization boundary for API requests. Server functions in `src/server` read the current request, and protected tRPC procedures check authorization again before accessing tenant data. The handlers in `src/routes/api` are thin HTTP adapters. The product modules remain organized by responsibility: `components` for UI, `lib/auth` for Better Auth, `lib/billing` for Stripe and credits, `trpc` for typed APIs, and `lib/db` for persistence. Keep database access and secrets in server functions, server-only modules or API handlers rather than code imported by the browser. The tRPC adapter is at `src/routes/api/trpc/$.ts`. See the [official routing guide](https://tanstack.com/start/latest/docs/framework/react/guide/routing), [server functions guide](https://tanstack.com/start/latest/docs/framework/react/guide/server-functions) and [execution model](https://tanstack.com/start/latest/docs/framework/react/guide/execution-model). --- ## Authentication **URL**: https://www.achromatic.dev/docs/starter-kits/pro-tanstack-drizzle/authentication **Description**: Better Auth sign-in, two-factor recovery and request-scoped authorization. ## Supported flows Better Auth handles email/password sign-in, email verification, password resets, optional Google sign-in, passkeys, TOTP two-factor authentication and backup-code recovery. Organization invitations and membership are handled by the organization plugin. `src/routes/api/auth/$.ts` forwards requests to Better Auth. The screens are under `src/routes/auth.*.tsx`; provider and session settings live in `config/auth.config.ts` and `lib/auth`. ## Email and Google setup Use a unique `BETTER_AUTH_SECRET` for each application and set `NEXT_PUBLIC_SITE_URL` to that application's actual origin. Configure `RESEND_API_KEY` and `EMAIL_FROM` for verification, password reset and invitation emails. For Google, configure `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`, then register this authorized redirect URI in your Google OAuth client: ```text https://your-domain.com/api/auth/callback/google ``` Use the complete URL, including the scheme and callback path. Register a separate callback for each deployed origin you use. Changing the application URL without updating Google causes a redirect-URI mismatch. ## Two-factor authentication and recovery TOTP is optional rather than required for every new account. Users who enable it receive backup codes and can regenerate them from Security settings. Two-factor enforcement also covers social and email-link sign-ins for accounts that require it. The verification screen supports using a different account and restarting an expired challenge. Account switching cancels the pending server-side challenge rather than merely navigating away. Incorrect codes remain retryable; a missing or expired challenge requires signing in again. Users should store backup codes somewhere safe before relying on two-factor authentication. Admin recovery is a privileged support action, not a public bypass. ## Server-side authorization Dashboard routes load request-scoped session data. Organization routes check membership, and admin routes check the platform role. These UI route guards improve navigation but do not replace authorization inside API handlers, server functions or tRPC procedures. Pass the current request's headers to `getSessionForHeaders` and organization helpers from `lib/auth/request.ts`. Do not keep a user's identity or organization in a module-global variable during SSR. Sensitive client requests are bound to the account that rendered the page. Preserve that account-scope header when extending the clients; a stale tab should ask the user to reload rather than operate as a different account. ## Account and organization ownership An account cannot be deleted while it is the sole owner of an organization. Transfer ownership or delete the organization first. The same ownership rule prevents a sole owner from leaving an organization and abandoning its remaining members. See [Better Auth's TanStack integration](https://better-auth.com/docs/integrations/tanstack) for the framework adapter. The shipped kit adds its own account-scope, recovery and authorization protections around that integration. --- ## Billing **URL**: https://www.achromatic.dev/docs/starter-kits/pro-tanstack-drizzle/billing **Description**: Configure Stripe plans, checkout, webhooks and credit accounting. ## Plans and entitlements Plans and public price identifiers are configured in `config/billing.config.ts`. Server-side billing and credit accounting live in `lib/billing`, with authorized operations exposed through tRPC. The kit supports subscriptions, one-time purchases, per-seat pricing, credits and server-side plan entitlements. Configure your own Stripe products and prices; the example price IDs are not usable products in your account. Set `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` and the applicable `NEXT_PUBLIC_STRIPE_PRICE_*` values in the environment. Keep Stripe test and live configuration separate. ## Hosted or embedded Checkout Hosted Stripe Checkout is the default and recommended starting point: ```text STRIPE_CHECKOUT_MODE=hosted ``` Optional embedded Checkout uses the included modal. To enable it, set `STRIPE_CHECKOUT_MODE=embedded` and configure `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` from the same Stripe account and mode as the secret key. The browser reads this through the kit's public environment configuration, not a raw `process.env` access. Public environment changes require a new build. A missing embedded publishable key should be fixed in configuration; do not expose the Stripe secret key to the browser. ## Webhooks The endpoint is `/api/webhooks/stripe`, implemented by `src/routes/api/webhooks/stripe.ts` and the shared handler in `lib/billing/webhook-handler.ts`. For local testing: ```bash npm run stripe:listen ``` Copy the signing secret printed by the Stripe CLI into your local environment. A Stripe Dashboard endpoint has its own signing secret; it is not interchangeable with the local listener secret. For production, create a Stripe webhook endpoint at: ```text https://your-domain.com/api/webhooks/stripe ``` Use the handled-event list in `.env.example` when selecting events. Ensure Stripe can reach the endpoint: a deployment-protection login page is not a successful delivery. Verify delivery status in Stripe after configuration. ## Payment correctness A checkout success redirect is not proof of payment. Verified webhook processing updates subscription, order and credit state. Event claims and transaction references prevent duplicate fulfillment when Stripe retries or delivers related events more than once. When applications share a Stripe account, the handler ignores events for customers not associated with an organization in this application's database. Metadata alone does not grant access to an organization. Keep entitlement, billing-management and credit checks on the server. Organization owners and admins can manage billing; ordinary members should not gain access by calling an endpoint directly. The protected admin panel also includes manual subscription-access controls. These are application access grants, not a substitute for charging a customer or modifying a Stripe invoice. --- ## Database **URL**: https://www.achromatic.dev/docs/starter-kits/pro-tanstack-drizzle/database **Description**: Configure PostgreSQL and Drizzle in the TanStack Start edition. Set `DATABASE_URL` in `.env` to a PostgreSQL connection string. Authentication, organizations, billing and application data use the same database. The schema is in `lib/db/schema`; committed SQL migrations are in `lib/db/migrations`. After changing the schema, run `npm run db:generate`, review the generated SQL and run `npm run db:migrate`. Apply those same committed migrations in production. ```bash npm run db:generate npm run db:migrate npm run db:studio ``` `npm run db:push` is only for disposable local prototyping because it changes the database without producing migration history. Keep tenant-owned queries scoped by organization ID: route-level membership checks do not replace authorization inside mutations or background work. --- ## Deployment **URL**: https://www.achromatic.dev/docs/starter-kits/pro-tanstack-drizzle/deployment **Description**: Build, configure and verify the TanStack Start Drizzle edition. ## Runtime and build The application builds with Vite and runs through Nitro. Use the patched Node.js 22 version pinned in the repository and configure environment variables before building. At minimum, set `DATABASE_URL`, a fresh `BETTER_AUTH_SECRET` and `NEXT_PUBLIC_SITE_URL` with your public HTTPS origin. Add email, Google, Stripe, S3 and AI credentials only for the providers you intend to use. ```bash npm ci npm run build npm run db:migrate npm run start ``` The standalone server entry point is `.output/server/index.mjs`. `npm run start` launches it with the production environment. Apply committed database migrations as a controlled deployment step; do not use `db:push` against a production database. ## Vercel The repository's `vercel.json` selects the TanStack Start framework. Link the intended project and team, configure its production environment, build, and test the deployment before assigning your public domain. The standard Vercel build does not replace a database-migration step. Apply migrations against the intended database using your deployment process. Keep database and server regions close to each other. If you clone a demo configuration, replace its database URL, auth secret, provider credentials and price IDs. Do not reuse a demo's production secrets. ## Public and private environment values Vite embeds public environment values at build time. Changing `NEXT_PUBLIC_SITE_URL`, a public Stripe key or a public price ID requires a new build. Never prefix secrets with `NEXT_PUBLIC_` or `VITE_`. The kit normalizes the public deployment metadata needed for trusted origins across Vercel's build and runtime environments. This does not expose server secrets or remove the need to set the correct site URL. ## Provider checklist - **Email:** verify the sending domain and test verification, password reset and invitation delivery. - **Google:** register the exact `/api/auth/callback/google` URL for the public application origin. - **Stripe:** use an endpoint-specific signing secret at `/api/webhooks/stripe` and confirm a test event is delivered. Hosted Checkout is the default. - **Storage:** configure the existing S3-compatible bucket and test avatar and organization-logo uploads. The included server upload route does not require browser-upload CORS. - **Observability:** configure Sentry as described in `README_OBSERVABILITY.md` and inspect runtime errors without logging credentials. ## Before going live Run type checks, lint, unit tests and a production build. In the deployed application, test sign-up and verification, sign-in and logout, two-factor recovery, organization membership, owner/admin/member permissions, uploads, checkout and webhook delivery. See [TanStack's hosting guide](https://tanstack.com/start/latest/docs/framework/react/guide/hosting), its [environment-variable guide](https://tanstack.com/start/latest/docs/framework/react/guide/environment-variables) and [Vercel's TanStack Start guide](https://vercel.com/docs/frameworks/full-stack/tanstack-start). --- ## Introduction **URL**: https://www.achromatic.dev/docs/starter-kits/pro-tanstack-drizzle **Description**: Build with the TanStack Start and Drizzle edition of Achromatic. The TanStack Start editions are two additional Achromatic starter kits, not replacements for the Next.js editions. This kit combines TanStack Start, TanStack Router, Better Auth, tRPC, Stripe and PostgreSQL with Drizzle. The marketing site, account dashboard, organization dashboard, admin panel, blog and documentation run in one application. Authentication, team management, subscriptions, credits, transactional emails and AI chat are already connected. The structure is intentionally a single application, without a monorepo or an internationalization layer. ## Choose your edition Use this edition for TanStack Start's file-based routing and server functions with Drizzle. Use the [Next.js + Drizzle edition](/docs/starter-kits/pro-nextjs-drizzle) if your product is built around the Next.js App Router. All four current editions are included in the same purchase. ## Start building 1. Follow [Setup](/docs/starter-kits/pro-tanstack-drizzle/setup) to install the kit and run it locally. 2. Read [Architecture](/docs/starter-kits/pro-tanstack-drizzle/architecture) and [Database](/docs/starter-kits/pro-tanstack-drizzle/database) before adding features. 3. Configure [Authentication](/docs/starter-kits/pro-tanstack-drizzle/authentication), [Billing](/docs/starter-kits/pro-tanstack-drizzle/billing) and [File storage](/docs/starter-kits/pro-tanstack-drizzle/storage) for the providers you need. 4. Complete the [Deployment checklist](/docs/starter-kits/pro-tanstack-drizzle/deployment) before going live. The repository also includes focused `README_*.md` guides for auth, billing, email, storage, AI and observability. Repository access is private; if your invitation is missing, [contact support](/contact) with your GitHub username. --- ## Setup **URL**: https://www.achromatic.dev/docs/starter-kits/pro-tanstack-drizzle/setup **Description**: Install and run the TanStack Start Drizzle starter kit locally. ## Requirements Use Node.js 22. The repository pins **22.23.4** in `.nvmrc`; use that patched version or a compatible patched Node.js 22 release. You also need PostgreSQL, plus Docker if you want to use the included local database. Clone the private repository after accepting your GitHub invitation: ```bash git clone https://github.com/achromaticlabs/pro-tanstack-drizzle.git my-app cd my-app cp .env.example .env ``` Before installing, edit `.env`: - Set `DATABASE_URL` to your PostgreSQL database. The example file and `docker-compose.yml` describe the included local instance. - Replace the example `BETTER_AUTH_SECRET` with a fresh random secret. Do not reuse a demo application's secret. - Set `NEXT_PUBLIC_SITE_URL=http://localhost:3000`. - Configure `RESEND_API_KEY` and `EMAIL_FROM` to complete email/password sign-up, password resets and organization invitations. ## Run locally ```bash npm ci npm run docker:up npm run db:migrate npm run dev ``` Open `http://localhost:3000`. If you already have PostgreSQL, set `DATABASE_URL` for that instance and skip `npm run docker:up`. If port 5432 is occupied, do not start a second database on the same port. Use committed Drizzle migrations to create the tables. Generating a migration and applying it are separate commands. ## Create an account A new email/password account must verify its email address before signing in. The kit sends a real verification email through Resend; it does not print a usable verification link to the terminal. Use a verified sending domain and a recipient your Resend account is permitted to email. Google sign-in is optional and needs its own OAuth configuration. Stripe, AI and S3-compatible storage can be configured when you need those features; they are not prerequisites for rendering the homepage. Keep secrets unprefixed. Variables prefixed with `NEXT_PUBLIC_` or `VITE_` can be exposed to browser code. ## Validate changes ```bash npm run typecheck npm run lint npm run test:unit -- --run npm run build ``` Continue with [Database](/docs/starter-kits/pro-tanstack-drizzle/database), [Authentication](/docs/starter-kits/pro-tanstack-drizzle/authentication) and [Deployment](/docs/starter-kits/pro-tanstack-drizzle/deployment). For framework fundamentals, see the [official TanStack Start documentation](https://tanstack.com/start/latest/docs/framework/react/overview). --- ## File storage **URL**: https://www.achromatic.dev/docs/starter-kits/pro-tanstack-drizzle/storage **Description**: Upload avatars and organization logos to private S3-compatible storage. ## Configure a bucket The kit supports S3-compatible storage, including Cloudflare R2. Set the bucket name in `NEXT_PUBLIC_IMAGES_BUCKET_NAME` and configure `S3_ENDPOINT`, `S3_REGION`, `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` on the server. Use credentials restricted to the bucket operations your application needs. Never put storage credentials in a `NEXT_PUBLIC_` or `VITE_` variable, commit them to Git or return them to the browser. ## Included upload flow The profile-avatar and organization-logo controls use the existing crop dialog, then post the cropped image to `/api/storage/upload`. The application server writes the object to the configured bucket with its S3 credentials. The server checks: - A trusted request origin and an authenticated session. - The account that rendered the calling page. - The intended active organization and an owner or admin role for logo uploads. - A PNG or JPEG content type matching the file signature. - A nonempty body no larger than 2 MB, enforced while reading the body as well as from its declared length. Object keys are generated on the server. The caller cannot choose another user's object path or an arbitrary bucket. Upload requests and provider calls have deadlines. ## CORS and shared demo buckets The included uploads go to the application's own origin, not directly from the browser to S3. They therefore do **not** require a bucket CORS policy. An existing compatible bucket can be reused without adding another browser origin to its CORS rules. If you build a separate direct-to-bucket upload flow, configure that flow's CORS, content validation and permissions independently. Do not open the bucket publicly or allow all origins just to bypass an upload error. ## Image delivery The bucket itself stays private. The `/storage/` route redirects image reads to temporary presigned download URLs. The UI's `useStorage` hook and avatar/logo components handle those paths. Profile pictures and organization logos are display assets. For confidential files, add an authorization check to the download path and use a separate storage policy rather than assuming an unguessable image URL is sufficient. See `README_STORAGE.md` in your repository for the source entry points.