# AI app builders

> Where to store the secret key in v0, Lovable, Bolt and Replit, how to keep it out of client code, and how previews and platform hosts work.

Source: https://esigncomply.com/docs/guides/ai-builders

AI app builders such as v0, Lovable, Bolt and Replit write and host an application for you. The Esign Comply integration is the same as anywhere else: your server holds a secret key and creates sessions, and the browser holds only a short-lived session client token. What changes is where the secret lives, which host your preview runs on, and how the domain is verified.

This page describes mechanisms, not menus. Builders rename their settings often. Look for the builder's "environment variables" or "secrets" setting for server-side code.

## The credentials

| Credential | Looks like | Who holds it |
|---|---|---|
| Secret API key | `esc_test_us_...`, `esc_live_us_...` | Server code only, read from a secret store |
| Webhook signing secret | `whsec_...` | Server code only |
| Session client token | `esc_ct_...` | The signer's browser, in memory, for one session |

There are no publishable keys. Nothing that starts with `esc_test_` or `esc_live_` ever belongs in code that runs in a browser.

## You create the account

You create the account and accept the terms once. No card. After that your AI agent can do the rest: create keys, register documents, build the flow, verify the domain and go live.

To hand over, start at [`/signup?next=/dashboard/agent`](https://esigncomply.com/signup?next=/dashboard/agent). Sign-up ends on **Agent access**, where you press **Create agent token**. The token starts with `esc_agent_`, acts as you with your role, expires after the time you choose and can be revoked there at any time. The agent stores it as `ESIGNCOMPLY_AGENT_TOKEN` in the builder's secret setting and uses it two ways: it logs in to the dashboard at `/agent-login`, or it calls the [agent account API](https://esigncomply.com/docs/api/agent.md). With the token it creates the test key, registers and verifies the domain, and creates the live key when you say go live. The steps are in the [guide for AI agents](https://esigncomply.com/agents.md).

A key is shown once, when it is created. It belongs in the builder's secret setting. Chat messages can end up in generated source, in logs and in project history, so keys and tokens stay out of the chat: the agent fetches its keys with the agent token and writes them to the secret setting. See the credential rules at [/auth.md](https://esigncomply.com/auth.md) and the agent runbook at [/setup.md](https://esigncomply.com/setup.md).

## Where the key goes

| Builder | What it usually generates | Where to store the key | Where sessions are created |
|---|---|---|---|
| v0 | A Next.js application deployed on Vercel | The project's environment variables, without a `NEXT_PUBLIC_` prefix | Route handlers and server actions |
| Lovable | A browser application with a hosted backend for data, auth and functions | The secrets of the backend functions | A backend function |
| Bolt | Varies with the stack you asked for. Often a browser application, sometimes with a server | The project's server-side environment variables or backend function secrets | Server routes or a backend function |
| Replit | An application with a server process | The workspace secrets, which the server reads as environment variables | Server routes |

Use these names everywhere so that generated prompts and code line up:

```bash
ESIGNCOMPLY_API_KEY=esc_test_us_...
ESIGNCOMPLY_WEBHOOK_SECRET=whsec_...
```

### If the application has no server

A browser-only application, such as a single-page app built with a bundler, has nowhere safe to keep a secret. Every variable the bundler can see is shipped to the browser. Do not put the key there, under any prefix.

Add a small server piece instead: a backend function, a serverless function or a server route. It does two jobs, and only these two need the key:

1. Create the session and return the client token.
2. Confirm the record before your application grants access.

A backend function that creates a session, written with `fetch` so it runs on any server runtime:

```ts
// A backend function, for example supabase/functions/start-ceremony/index.ts
const cors = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response("ok", { headers: cors });

  // 1. Authenticate YOUR user here with your own auth, and load their ID and email
  //    from your database. Do not accept them from the request body.
  const user = await getSignedInUser(req); // your code
  if (!user) return new Response("Unauthorized", { status: 401, headers: cors });
  // The page sends 1 at first and a higher number when it needs a new session (expired, inputs changed).
  const { attempt = 1 } = (await req.json().catch(() => ({}))) as { attempt?: number };

  // 2. Create the session with the secret key, which only this function can read.
  const res = await fetch("https://esigncomply.com/v1/sessions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${Deno.env.get("ESIGNCOMPLY_API_KEY")}`,
      "Content-Type": "application/json",
      "Idempotency-Key": `signup-${user.id}-${Number(attempt) || 1}`,
    },
    body: JSON.stringify({
      profile: "prof_signup_4f1a",
      signer: { external_id: user.id, email: user.email, class: "consumer", country: user.country },
      documents: [
        { document: "doc_8Hq2", version: "current" },
        { document: "doc_Pv71", version: "current" },
      ],
      context: { url: `${req.headers.get("origin")}/signup`, purpose: "account_signup" },
    }),
  });
  const session = await res.json();
  if (!res.ok) {
    return Response.json({ error: session.error?.code ?? "session_failed" }, { status: 502, headers: cors });
  }

  // 3. Save session.id and the pinned version IDs in your own database for confirmation.
  await saveCeremony(user.id, session.id, session.documents.map((d: { version_id: string }) => d.version_id)); // your code

  // 4. Send the browser only what it needs. Never the key, never the whole response.
  return Response.json(
    {
      clientToken: session.client_token,
      apiUrl: session.api_url,
      documents: session.documents.map((d: { document_id: string; version_id: string; title: string }) => ({
        documentId: d.document_id,
        versionId: d.version_id,
        title: d.title,
      })),
    },
    { headers: cors },
  );
});
```

The browser then attaches with the client token, exactly as in the [quickstart](https://esigncomply.com/docs/quickstart.md):

```ts
import { EsignComply } from "@esigncomply/browser";

const ceremony = await EsignComply.attach({ clientToken, apiUrl });
```

Write a second function for [server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md). Do not let the browser decide that an acceptance happened, and do not let it write to your acceptances table. With row-level security, give that table a read policy only, and write to it from the backend function.

## Keep the key out of client code

Rules for the tool, and for you when you review what it wrote:

- Only server code reads `ESIGNCOMPLY_API_KEY`: route handlers, server actions, backend functions.
- No public prefix, ever. Variables named `NEXT_PUBLIC_…`, `VITE_…`, `PUBLIC_…`, `REACT_APP_…` or `EXPO_PUBLIC_…` are copied into the browser bundle by design.
- The key is never written in source code, in a prompt, in a comment or in a commit. `.env` files stay out of version control.
- No file marked `"use client"` imports the `esigncomply` server package. In Next.js, start the module that creates the client with `import "server-only"`.
- The browser calls Esign Comply directly with the client token. Do not proxy `@esigncomply/browser` calls through your own server, and do not build a proxy route that adds the secret key to browser requests.
- A server route returns `client_token`, `api_url` and the document version IDs. It does not return the key, and it does not echo environment variables in error messages.

The API helps a little. `EsignComply.attach` refuses anything that is not a client token, endpoints for secret keys refuse client tokens with [`insufficient_permission`](https://esigncomply.com/docs/api/errors.md#insufficient_permission), and a key created for an application has the `recording_access` permission by default, which cannot download evidence reports, evidence packages or certificates. None of that makes a leaked key safe. Treat it as a password.

### Check the bundle

After a production build, search the files that are served to browsers:

```bash
grep -RIl -e "esc_test_" -e "esc_live_" -e "ESIGNCOMPLY_API_KEY" .next/static dist build public 2>/dev/null \
  && echo "LEAK: the key or its variable name is in client files" \
  || echo "clean"
```

Then open the browser's network panel on your signing page. Requests to `esigncomply.com` must carry `Authorization: Bearer esc_ct_...` and nothing else. No request from the browser to your own server should contain or return a value that starts with `esc_test_` or `esc_live_`.

Check the repository too:

```bash
git ls-files | grep -E '(^|/)\.env' && echo "An env file is committed" || echo "clean"
git grep -n -e "esc_test_" -e "esc_live_" -e "whsec_" || echo "clean"
```

## Previews and the test allowlist

Test keys work on `localhost` and `127.0.0.1` with no setup. A builder's preview runs on the builder's own host, so add that host to your test origins first. Otherwise session creation and browser calls return [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch), and the message names the origin that was refused.

Add hosts in the dashboard under Domains, or with the API:

```bash
curl -X PATCH https://esigncomply.com/v1/domains/dom_4Kx9 \
  -H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "test_origins": ["my-project-preview.example-builder.app"] }'
```

- List the exact preview host of your project. An entry also covers its subdomains, so do not list a platform's shared suffix.
- Some builders run the preview in a frame on a different host than the one in your address bar. Use the origin named in the `domain_mismatch` message.
- Preview hosts change between projects and sometimes between sessions. Update the list when the host changes. You can list up to 25.

See [Test mode](https://esigncomply.com/docs/guides/test-mode.md).

## Going live on a platform host

To record live you need a verified domain. A host on a shared platform suffix, such as `myapp.vercel.app`, `myapp.lovable.app` or `myapp.replit.app`, registers as its own domain and verifies with a file, because you cannot add DNS records there:

```text
https://myapp.lovable.app/.well-known/esigncomply.txt
```

The file contains the token from the dashboard. In most generated projects, a file placed under the `public` folder at `.well-known/esigncomply.txt` is served at that address. Check it before you trigger verification:

```bash
curl -i https://myapp.lovable.app/.well-known/esigncomply.txt
```

You should get status `200` and the token as plain text. A single-page application that answers every unknown path with its HTML page will return `200` with the wrong body. If that happens, add the static file, or a server route for that exact path.

If you plan to use your own domain, register that domain instead and verify by DNS. Moving from a platform host to a custom domain later is a domain change, and a subscription can change its domain once per 12 months without contacting support. See [Register a domain](https://esigncomply.com/docs/guides/domains.md).

Set the live key only in the production environment of the builder. Keep the test key for previews and development.

## What to tell the builder

The fastest route is a generated prompt: choose your use case, your stack and your tool, and paste the result into the builder. See the [prompt generator](https://esigncomply.com/product/prompt-generator). The prompt names the environment variables and never contains a key.

If you write your own instructions, include these rules. They are the same ones in [/llms.txt](https://esigncomply.com/llms.txt):

```text
- Packages that exist: esigncomply (server), @esigncomply/browser (client). Do not invent others.
- Read ESIGNCOMPLY_API_KEY only in server code. Never place the API key in client code.
- Create every session on the server. Send only client_token to the browser.
- Never pre-check an assent control and never submit on the user's behalf.
- Pass signer.region from the form or account data. Never infer it from IP.
- Read required_steps and required_strings from the session. Do not hard-code steps or legal wording.
- Grant access only after the server has confirmed the record with the secret key.
- When a session is refused, stop the flow and tell the person. Never fall back to an acceptance with no record.
- If you are unsure how to implement a step, stop and ask.
```

## A checklist the tool can run

1. **The key works and is a test key.** From server code or a terminal with the secret loaded:

   ```bash
   curl -s https://esigncomply.com/v1/usage -H "Authorization: Bearer $ESIGNCOMPLY_API_KEY"
   ```

   A `200` response means the key is valid. [`invalid_api_key`](https://esigncomply.com/docs/api/errors.md#invalid_api_key) means it was copied wrong or revoked.

2. **The bundle is clean.** Run the `grep` commands above. All three must print `clean`.
3. **The browser holds only a client token.** Check the network panel as described above.
4. **The ceremony is recorded.** Complete it once on `localhost` or the preview. A test record appears in the dashboard with its findings.
5. **The interface passes the checker.** Run `npx esigncomply check --url http://localhost:3000/signup` and fix every finding marked `block`. See the [CLI](https://esigncomply.com/docs/sdk/cli.md).
6. **A forged result is refused.** Call your confirmation function with a made-up record ID. It must not grant access.

## If a key was exposed

Assume it is compromised, even if the exposure was brief.

1. Revoke the key in the dashboard, or with `DELETE /v1/api-keys/{id}` using a `full_access` key.
2. Create a new key and store it in the builder's secret setting.
3. Redeploy so the server picks up the new value.
4. Remove the old value from source, chat history you control and commit history where you can.
5. Review recent sessions and records in the dashboard for activity you do not recognize.

Esign Comply stores only a prefix and a hash of each key, so a lost key cannot be shown again. Create a new one.
