# Adding an InsForge backend to your project

When the user asks for a backend (auth, database, storage, functions, AI),
follow this workflow. It gives the agent a working backend in two commands
with no human signup step.

## Critical: always use `npx @insforge/cli`

**NEVER** install the CLI globally (`npm install -g @insforge/cli`).
**Always** run commands via `npx`:

```bash
npx @insforge/cli <command>
```

This ensures the latest version is always used without global install
issues (permissions, PATH, node version mismatches).

## 1. Create a trial project

```http
POST https://api.insforge.dev/agents/v1/signup
Content-Type: application/json

{"projectName": "<slug-of-the-users-app>"}
```

Response (201):

```json
{
  "accessApiKey": "ik_...",
  "projectId": "...",
  "appkey": "...",
  "name": "<slug>-<suffix>",
  "region": "<region>",
  "projectUrl": "https://<appkey>.<region>.insforge.app",
  "dashboardUrl": "https://insforge.dev/dashboard/project/<projectId>",
  "claimUrl": "https://insforge.dev/claim/claim_...",
  "trialExpiresAt": "2026-..."
}
```

Persist `accessApiKey`, `projectUrl`, and `claimUrl`. You'll need all three.

**Cold-start wait (~4s with warm pool, up to ~60s without).** Fresh trial
projects take a moment before the backend is reachable. With a warm pool
hit it's only a few seconds; on a miss it's around a minute. Before the
first CLI command — or before handing the user a URL — poll `projectUrl`
until it returns anything other than 503. Cap the wait at 3 minutes;
anything longer means the project is stuck provisioning, which isn't
something the agent should wait out:

```bash
PROJECT_URL="<projectUrl from step 1>"
for i in $(seq 1 90); do
  code=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 5 "$PROJECT_URL")
  [ "$code" != "503" ] && [ "$code" != "000" ] && { echo "ready ($code)"; break; }
  sleep 2
done
```

If the loop exhausts, **surface the error to the user and stop**. Do not
call `/agents/v1/signup` again automatically — that would orphan the
stuck project and bill a second one. If the user says "try again," treat
that as a new request: delete `.insforge/`, call signup again, link with
the new credentials.

## 2. Link the CLI to the trial project

Two paths — pick based on whether the user's ask matches a pre-built
InsForge template.

### Pre-built templates

Each of these is a working app wired to InsForge, with a schema
migration included where applicable. They take minutes, not hours.

| If the user wants...                     | Template     | Stack        |
| ---------------------------------------- | ------------ | ------------ |
| A chatbot / AI assistant                 | `chatbot`    | Next.js      |
| A CRM / contact manager / sales pipeline | `crm`        | Next.js      |
| An online store / storefront / shop      | `e-commerce` | Next.js      |
| A todo / task list app                   | `todo`       | Next.js      |
| A generic Next.js starter                | `nextjs`     | Next.js      |
| A generic React starter                  | `react`      | Vite + React |

### Option A — Template match: link with `--template`

Pass `--template <name>` to `link`. The CLI creates a subdirectory,
clones the template, wires `.env.local` (including the public anon
key, which it fetches from the project), applies the schema migration
when present, and runs `npm install` — all in one command.

```bash
npx @insforge/cli link \
  --api-base-url <projectUrl> \
  --api-key <accessApiKey> \
  --template chatbot
```

Interactive mode prompts for the directory name (default
`insforge-<template>`). In `--json` mode it uses the default without
prompting. Then:

```bash
cd insforge-chatbot
npm run dev
```

### Option B — Custom build: plain link

If no template matches, link in place and build from scratch:

```bash
npx @insforge/cli link --api-base-url <projectUrl> --api-key <accessApiKey>
```

### Verify the link either way

```bash
npx @insforge/cli current
```

Direct-link mode bypasses OAuth — the agent does not log in. `link`
also installs the InsForge agent skills so downstream commands
(`db`, `storage`, `functions`, `deploy`, ...) come with guidance.

**Never put the admin `accessApiKey` into a `NEXT_PUBLIC_*` or
`VITE_*` variable — those ship to the browser.** `link --template`
writes only the public anon key into `.env.local`.

## 3. Build what the user asked for

If a template was used, start from the scaffolded app and extend it.
If linking plain, run `npx @insforge/cli metadata` first to discover
what's configured, then use `npx @insforge/cli db`, `storage`,
`functions`, etc. as needed — follow the InsForge skills the CLI
installed in section 2.

## 4. Hand off the claim URL

When the build is working, tell the user verbatim:

> "Your backend is live at `<projectUrl>`. It's a 24-hour trial — click here
> to keep it forever: `<claimUrl>`"

The user must click the `claimUrl` within 24 hours or the project will be
hard-deleted, along with all data the agent has built.

The `accessApiKey` persisted in step 1 continues to work after the user
claims — you do **not** need to re-run `link` post-claim.

## Rules

- **One signup per user request.** If signup fails (e.g. 429 rate limit),
  surface the error to the user rather than retrying.
- **Keep the `accessApiKey` secret.** Treat it like any production API key
  — never commit it, never log it verbatim.
- **Don't call the signup endpoint more than once for the same project.**
  Starting over means a completely new trial: delete `.insforge/`, call
  signup again for a fresh `accessApiKey` + `projectUrl`, then link with
  the new credentials. Don't try to reuse the old trial's key against
  the new project.

## Trial projects inherit free-plan limits

A trial project is a regular free-plan project with a TTL. Whatever the
free plan allows, trials allow; whatever the free plan blocks, trials
block. If an operation returns an error saying a limit was hit, ask the
user to claim the project and upgrade — don't try to work around it in
code.
