> ## Documentation Index
> Fetch the complete documentation index at: https://docs.totalmod.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Get started

> Add totalmod to a Next.js app step by step, from npx totalmod init to the first feature a user asks for.

Add totalmod to a Next.js app: a **Request a feature** button for your users, an AI interviewer that turns a request into a spec, a GitHub Action that builds it on a branch, a private preview on mock data, and a merge that only you can make.

Plan for about an hour, most of it in the GitHub and Vercel settings.

## Before you start

You need:

* **A Next.js app using the App Router**, on React 19 and Node 24 or later.
* **A GitHub repository** for the app. The build runs in GitHub Actions.
* **Vercel preview deployments** from that repository, through Vercel's GitHub integration. That's how requesters get a preview of their feature.
* **An Anthropic API key.** The interviewer and the build agent use Claude.
* **A sign-in system.** totalmod asks your app who the signed-in user is.

## Set up

**1. Add totalmod to your app**

In your app's folder, run:

```bash theme={null}
npx totalmod init
```

It adds these files and never edits your existing ones. If a file already exists, it's kept unless you pass `--force`.

| File | What it's for |
| - | - |
| `app/api/totalmod/[...totalmod]/route.ts` | The totalmod API your widget talks to |
| `lib/totalmod.ts` | Who is asking, and where requests are kept |
| `components/totalmod-widget.tsx` | The **Request a feature** button |
| `totalmod.config.yaml` | Your policy: who may ask, budgets, allowed paths |
| `flags/totalmod.flags.json` | One flag per built feature |
| `seed/mock.ts` | Mock data for previews |
| `.github/workflows/totalmod-build.yml` | Builds a confirmed spec on a branch |
| `.github/workflows/totalmod-release.yml` | Turns flags on after you merge, and handles rollout |

If your app uses a `src/` folder, the app files go under `src/`. These files are licensed MIT-0, so they're yours to change.

Then install the runtime packages:

```bash theme={null}
npm install @totalmod/server @totalmod/widget @totalmod/flags
```

**2. Tell totalmod who is asking**

Open `lib/totalmod.ts` and make `getRequester` return the signed-in user, or `null` for a signed-out visitor:

```ts lib/totalmod.ts theme={null}
import { auth } from "@/auth"; // your auth library

export async function getRequester(request: Request): Promise<Requester | null> {
  const session = await auth();
  if (!session) return null;
  return { id: session.user.id, plan: session.user.plan, role: session.user.role };
}
```

The `id` is hashed before it leaves your app. `plan` and `role` are optional, and decide who may send requests.

The same file sets where requests are stored. Implement `RequestStore` against a table in your own database before going live. It has five methods: `create`, `get`, `update`, `countSince` and `latestByUser`. The [demo app](https://github.com/sumanprime/totalmod/blob/main/examples/demo-notes/lib/totalmod.ts) has a Drizzle version.

> [!NOTE]
>
> The generated `memoryRequestStore()` is fine for trying totalmod out, but it loses requests on restart.

**3. Show the widget**

Render the widget once, in your root layout:

```tsx app/layout.tsx theme={null}
import { TotalmodWidget } from "@/components/totalmod-widget";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <TotalmodWidget />
      </body>
    </html>
  );
}
```

It renders nothing for users who can't send requests. To match your brand, set the `--tms-*` custom properties (`--tms-accent`, `--tms-bg`, `--tms-text`, …) on `.tms-root`.

Then add two packages to `serverExternalPackages`. The flag provider must not be bundled:

```ts next.config.ts theme={null}
const nextConfig = {
  serverExternalPackages: ["@totalmod/flags", "@openfeature/flagd-provider"],
};

export default nextConfig;
```

**4. Set up mock data for previews**

Every preview runs on mock data, with no way to reach production. Your app has to support this:

* **With `TOTALMOD_MODE=mock`, use an in-memory database** seeded from `seed/mock.ts`, never `DATABASE_URL`. Fill `seed/mock.ts` with users shaped like your real ones: one per plan and role, at realistic volumes.
* **Add a `/totalmod/preview` route** that turns the requester's signed link into a mock session:

```ts app/totalmod/preview/route.ts theme={null}
import { verifyPreviewToken } from "@totalmod/core";
import { redirect } from "next/navigation";

export async function GET(request: Request) {
  if (process.env.TOTALMOD_MODE !== "mock") return new Response("Not found.", { status: 404 });

  const token = new URL(request.url).searchParams.get("token") ?? "";
  const result = verifyPreviewToken(token, process.env.TOTALMOD_PREVIEW_SECRET ?? "");
  if (!result.ok) return new Response("This preview link is not valid.", { status: 401 });

  const { requester, plan = "free", role = "member" } = result.payload;
  // Create a mock user with this plan and role in the mock database, sign them in,
  // then send them into the app. Use your own database and session code here.
  await signInMockUser({ id: `preview-${requester}`, plan, role });
  redirect("/");
}
```

The [demo app's preview route](https://github.com/sumanprime/totalmod/blob/main/examples/demo-notes/app/totalmod/preview/route.ts) is a complete example.

**5. Set your policy**

`totalmod.config.yaml` is enforced by deterministic checks in CI, not by prompts:

| Setting | Default | What it does |
| - | - | - |
| `requesters` | `all` | Who may ask: `all`, `paying` (any plan except `free`), or a list of user ids |
| `budget.perRequestUsd` | `3` | Most Claude spend on one request |
| `budget.monthlyUsd` | `100` | Most Claude spend in a month |
| `iterations.max` | `3` | Fix rounds a requester gets |
| `paths.allowed` | `app`, `components`, `lib` | Where the build agent may change files |
| `paths.blocked` | `[]` | Extra blocked paths. Auth, billing, migrations, `.env*` and `.github` are always blocked |
| `paths.maxChangedLines` | `600` | Largest change a build may make |
| `flags.removeAfterDays` | `14` | Days after full rollout before a PR removes the flag |
| `telemetry` | `true` | Anonymous counts; set `false`, or `DO_NOT_TRACK=1`, to turn off |

Specs and fix requests that touch auth, billing, migrations, admin, secrets or CI are declined.

**6. Connect GitHub**

Create two secrets first. Any long random string works:

```bash theme={null}
openssl rand -hex 32   # run twice: one for TOTALMOD_PREVIEW_SECRET, one for TOTALMOD_WEBHOOK_SECRET
```

**A token.** Create a [fine-grained personal access token](https://github.com/settings/personal-access-tokens/new) for this one repository, with read and write access to **Contents**, **Issues** and **Pull requests**. Issues and PRs are created as you. For a team, a GitHub App with the same permissions is better; the [server README](https://github.com/sumanprime/totalmod/tree/main/packages/server#github-access-two-options) shows how.

**Actions settings.** In the repository, under **Settings → Secrets and variables → Actions**, add:

| Type | Name | Value |
| - | - | - |
| Secret | `ANTHROPIC_API_KEY` | Your Anthropic API key. It's the only secret the build agent sees. |
| Secret | `TOTALMOD_GITHUB_TOKEN` | The token |
| Variable | `TOTALMOD_TRUSTED_ACTORS` | The GitHub login that owns the token (or your App) |

**Webhook.** Under **Settings → Webhooks → Add webhook**:

* **Payload URL:** `https://<your app>/api/totalmod/webhooks/github`
* **Content type:** `application/json`
* **Secret:** your `TOTALMOD_WEBHOOK_SECRET`
* **Events:** choose individual events, then **Pull requests** and **Deployment statuses**

**7. Set the environment variables**

In your Vercel project, under **Settings → Environment Variables**. Production and Preview get different values on purpose:

| Variable | Production | Preview |
| - | - | - |
| `ANTHROPIC_API_KEY` | your key | **never** |
| `TOTALMOD_GITHUB_REPO` | `owner/name` | **never** |
| `TOTALMOD_GITHUB_TOKEN` | the token | **never** |
| `TOTALMOD_WEBHOOK_SECRET` | the webhook secret | **never** |
| `TOTALMOD_PREVIEW_SECRET` | the preview secret | the same value |
| `TOTALMOD_MODE` | unset | `mock` |
| `DATABASE_URL` and any other data access | as before | **never** |

> [!WARNING]
>
> Uncheck **Preview** on every production variable. A preview has no path to production data because it never gets the credentials.

**8. Check your setup**

```bash theme={null}
npx totalmod doctor
```

It checks your config, flags file and workflows, and lists the secrets to set. To also check the Vercel environment, set `VERCEL_TOKEN` and `VERCEL_PROJECT_ID` first (plus `VERCEL_TEAM_ID` for a team project). It fails if a credential is in Preview, or if `TOTALMOD_MODE` or `TOTALMOD_PREVIEW_SECRET` is missing there.

Fix anything it reports, then deploy.

## Try the loop

Sign in to your deployed app as a normal user and click **Request a feature**:

1. **Request.** Describe a feature in a sentence. The interviewer asks up to four questions, then shows a spec to confirm or edit once.
2. **Build.** Confirming files a GitHub issue labelled `totalmod:build`, holding only the spec. The build workflow checks the policy and budgets, has Claude Code build it on `totalmod/req-<id>`, checks the changed paths, and opens a draft PR with a risk summary.
3. **Preview.** Vercel deploys the branch on mock data. The widget shows the requester a private **Try it** link that only they can open, valid for 24 hours.
4. **Fix rounds.** The requester can ask for changes, up to `iterations.max` times. Each one is rewritten into concrete changes before it reaches the build agent.
5. **Approval.** **Looks good** marks the PR ready for your review.
6. **Release.** You review and merge. The feature turns on for the requester first, behind a flag. Add a label to the merged PR to go further: `totalmod:rollout-25` for 25% of users (any number from 1 to 99), `totalmod:ga` for everyone, or `totalmod:off` to switch it off. After `flags.removeAfterDays` at full rollout, a PR removes the flag.

Features are wrapped in `isRequestEnabled(user.id, reqId)` from `@totalmod/flags`. The build agent adds this for you.

## Try it without an API key

The interviewer can run on [Ollama](https://ollama.com) or [LM Studio](https://lmstudio.ai), so you can try the request flow with a model you already have. From a clone of the [totalmod repo](https://github.com/sumanprime/totalmod):

```bash theme={null}
pnpm i
TOTALMOD_LLM=ollama TOTALMOD_MODEL=qwen3.8 pnpm local:up
```

Then open [127.0.0.1:3200](http://127.0.0.1:3200), sign in and click **Request a feature**.

> [!NOTE]
>
> GitHub is stubbed in this demo, and only a model on the same machine is accepted, so this is for testing, not production.

## If something doesn't work

> [accordion] The widget doesn't show
>
> `getRequester` returned `null`, or `requesters` in `totalmod.config.yaml` excludes this user.

> [accordion] The build doesn't start
>
> Check that `TOTALMOD_TRUSTED_ACTORS` matches the account the issue was filed as, and that budgets aren't spent. The workflow comments on the issue when it stops.

> [accordion] No Try it link
>
> Check the webhook's events (Pull requests and Deployment statuses) and its secret, and that the preview deployment succeeded.

> [accordion] The preview link says it's not valid
>
> `TOTALMOD_PREVIEW_SECRET` must be the same in Production and Preview.

## Telemetry and license

totalmod sends anonymous counts, such as requests submitted and previews ready, and never request text, code, prompts or user ids. The CLI says so on first run. Turn it off with `DO_NOT_TRACK=1` or `telemetry: false`.

totalmod is free under the AGPL-3.0, or available under a [commercial license](https://github.com/sumanprime/totalmod/blob/main/COMMERCIAL-LICENSE.md) for closed-source products. Files that `npx totalmod init` adds are MIT-0.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.