# Local cloud development

Develop and test locally with `pnpm dev`, Vitest, or Node scripts directly against your real hosted ohmyho.st Dev (or Prod) database, private storage, transactional mail, AI gateway, Browser PDF, container jobs, and Native Auth — without running local Postgres, R2, or Resend emulators.

Full human-facing guide: <https://docs.ohmyho.st/local-development>.

## 1. Prerequisites and `.env.local`

Local cloud development uses an Owner API token (`projects:write`, or the narrower Owner-only `runtime:use` permission) and your project ULID. Keep `.env.local` out of Git and never expose `OHMYHOST_API_TOKEN` to browser bundles or client components.

Find your project ULID and organization ULID:

```sh
ohmyhost whoami --json
ohmyhost project list --json
```

Create an Owner API token in the portal (<https://app.ohmyho.st/tokens>, default full permission set) or, for least privilege, with the CLI (in a process without `OHMYHOST_TOKEN` set). The portal cannot narrow permissions; only the CLI `--permissions` option (also the REST `permissions` field and the local MCP `token_create` tool) can. Use `--permissions runtime:use` (CLI `>= 0.1.91`) so the local token can only call the Cloud Runtime Bridge and cannot modify projects or billing:

```sh
ohmyhost token create --organization "$ORGANIZATION_ID" --name local-dev \
  --permissions runtime:use --idempotency-key "local-dev-token-1" \
  --out "$HOME/.ohmyhost-local-token.env" --json
```

`ohmyhost token create --out` writes `OHMYHOST_TOKEN=...` (the CLI automation credential). Local runtime resolution reads `OHMYHOST_API_TOKEN` so your interactive CLI login and your app's local runtime token remain separate. Copy that token value into your app's `.env.local` as `OHMYHOST_API_TOKEN`:

```bash
OHMYHOST_API_TOKEN=sk_your_owner_api_token
OHMYHOST_PROJECT_ID=01M86PRYGH1168CQPQ2ZV519YZ

# Optional overrides:
# OHMYHOST_ENVIRONMENT=dev          # dev | prod (default: dev when present, else prod)
# OHMYHOST_AI_JURISDICTION=any      # any | eu (default: any; active EU-locked deployments stay eu)
# OHMYHOST_ENVIRONMENT_ID=01...     # optional explicit environment ULID to skip initial /runtime/resolve
```

| Variable                   | Required | Default                       | Purpose                                                                                                       |
| -------------------------- | -------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `OHMYHOST_API_TOKEN`       | Yes      | —                             | Owner API token with `projects:write` or `runtime:use`.                                                       |
| `OHMYHOST_PROJECT_ID`      | Yes      | —                             | Target project ULID from `ohmyhost project list --json`.                                                      |
| `OHMYHOST_ENVIRONMENT`     | No       | `dev` if present, else `prod` | Selects `dev` (Paid with Dev environment) or `prod` (Free or Prod-only projects, or explicit Prod targeting). |
| `OHMYHOST_AI_JURISDICTION` | No       | `any`                         | Selects `any` or `eu` for local AI calls. An active deployment locked to `eu` stays enforced as `eu`.         |
| `OHMYHOST_ENVIRONMENT_ID`  | No       | Resolved automatically        | Optional environment ULID; skips the cached `GET .../runtime/resolve` lookup.                                 |

**Environment safety:** On Free workspaces or Prod-only projects, omitting `OHMYHOST_ENVIRONMENT` targets `prod`. When working against `prod` or a project using shared Dev/Prod data, local writes modify real live data.

## 2. Install the runtime package alias

Install `@amerged/ohmyhost-runtime` under the `@ohmyhost/customer-runtime` import alias (the exact alias reported by `ohmyhost init --dry-run --json`) and commit the updated lockfile:

```json
{
  "dependencies": {
    "@ohmyhost/customer-runtime": "npm:@amerged/ohmyhost-runtime@0.1.98"
  }
}
```

Both `@ohmyhost/customer-runtime` (the alias required for hosted builds) and `@amerged/ohmyhost-runtime` export `resolveOhMyHostEnv` and `DATABASE_CLIENT_LIMITS` for both ESM (`import`) and Node 22.12+ CommonJS/`tsx` (`require()`).

## 3. Resolve bindings once with `resolveOhMyHostEnv`

Call `resolveOhMyHostEnv(workerEnv)` in server code only (it throws `runtime_env_invalid` in a browser):

- **Hosted (Cloudflare Workers Dev/Prod):** detects real hosted bindings on `workerEnv` and returns `workerEnv` untouched with zero network overhead.
- **Local (`pnpm dev`, Vitest, Node scripts):** reads `.env.local` / `process.env` and returns an identical frozen `env` object (`OHMYHOST_PROJECT_ID`, `OHMYHOST_ENVIRONMENT_ID`, `OHMYHOST_DATABASE`, `OHMYHOST_STORAGE_GATEWAY_URL`, `OHMYHOST_STORAGE_KEY`, `OHMYHOST_MAIL_GATEWAY_URL`, `OHMYHOST_MAIL_KEY`, `OHMYHOST_AI_BASE_URL`, `OHMYHOST_AI_KEY`, `OHMYHOST_BROWSER_BASE_URL`, `OHMYHOST_BROWSER_GATEWAY_URL`, `OHMYHOST_BROWSER_KEY`, `OHMYHOST_JOBS_BASE_URL`, `OHMYHOST_JOBS_TOKEN`, `OHMYHOST_AUTH`) backed by the Owner-authenticated Cloud Runtime Bridge on `https://app.ohmyho.st`.

### Next.js App Router (OpenNext)

In Next.js Route Handlers and Server Components, wrap `getCloudflareContext({ async: true })` in a `try/catch` so `next dev` falls back cleanly to `.env.local`:

```ts
import { getCloudflareContext } from "@opennextjs/cloudflare";
import { resolveOhMyHostEnv } from "@ohmyhost/customer-runtime";
import { createPrivateDatabaseClient } from "@ohmyhost/customer-runtime/database";
import { createNativeAuthServer } from "@ohmyhost/customer-runtime/auth-server";

export async function getAppServices() {
  let workerEnv: Record<string, unknown> | undefined;
  try {
    workerEnv = (await getCloudflareContext({ async: true })).env as Record<string, unknown>;
  } catch {
    workerEnv = undefined;
  }
  const env = await resolveOhMyHostEnv(workerEnv);
  return {
    env,
    db: createPrivateDatabaseClient(env.OHMYHOST_DATABASE),
    auth: createNativeAuthServer(env.OHMYHOST_AUTH),
  };
}
```

### Vite API companion, TanStack Start, Astro SSR, plain Worker, Vitest, and Node scripts

Pass the runtime `env` when present (or `undefined` in local scripts and tests):

```ts
import { resolveOhMyHostEnv } from "@ohmyhost/customer-runtime";
import { createPrivateDatabaseClient } from "@ohmyhost/customer-runtime/database";

export async function getServices(workerEnv?: Record<string, unknown>) {
  const env = await resolveOhMyHostEnv(workerEnv);
  return { env, db: createPrivateDatabaseClient(env.OHMYHOST_DATABASE) };
}
```

## 4. Use every bridged capability identically locally and in production

### PostgreSQL (`OHMYHOST_DATABASE`)

Always pass both `text` and `values` (use `values: []` when there are no parameters; omitting `values` fails locally with `database_query_invalid`):

```ts
import { createPrivateDatabaseClient } from "@ohmyhost/customer-runtime/database";

const db = createPrivateDatabaseClient(env.OHMYHOST_DATABASE);

// Single query (HTTPS)
const { rows } = await db.query({
  text: "SELECT id, title FROM public.items WHERE owner_id = $1 ORDER BY id DESC LIMIT 20",
  values: [userId],
});

// Atomic multi-statement transaction (up to 25 statements, HTTPS)
await db.transaction([
  {
    text: "UPDATE public.accounts SET balance = balance - $1 WHERE id = $2",
    values: [100, fromId],
  },
  { text: "UPDATE public.accounts SET balance = balance + $1 WHERE id = $2", values: [100, toId] },
]);

// Held connection for read-decide-write (uses a single-use 30s HMAC WebSocket ticket; Node 22+ WebSocket)
await db.withConnection(async (conn) => {
  await conn.query({ text: "BEGIN", values: [] });
  const existing = await conn.query({
    text: "SELECT status FROM public.orders WHERE id = $1 FOR UPDATE",
    values: [orderId],
  });
  if (existing.rows[0]?.status === "open") {
    await conn.query({
      text: "UPDATE public.orders SET status = $1 WHERE id = $2",
      values: ["paid", orderId],
    });
  }
  await conn.query({ text: "COMMIT", values: [] });
});

// Identity-scoped Row-Level Security transaction (also over a single-use 30s HMAC WebSocket ticket)
const ownRows = await db.withRls({ subject: userId }, async (trx) => {
  return trx.query({ text: "SELECT id, title FROM public.items", values: [] });
});
```

Your `OHMYHOST_API_TOKEN` is exchanged over HTTPS for a single-use 30-second HMAC WebSocket ticket and never appears in a WebSocket URL.

**Database client limits (`DATABASE_CLIENT_LIMITS`) and column types:**

- Import `DATABASE_CLIENT_LIMITS` from `@ohmyhost/customer-runtime/database` (enforced identically locally and hosted): `maxQueryBytes` 64 KiB, `maxParameters` 100 per statement (batch inserts or pass arrays with `UNNEST`), `maxParameterBytes` 1 MiB total per query/transaction, `maxJsonParameterBytes` 64 KiB estimated size of a single object or array parameter (string and key bytes, 8 per number, 24 per date; `UNNEST` arrays included), `maxKeyBytes` 128 bytes, `maxTransactionQueries` 25 statements, `maxResultRows` 1,000 rows, `maxResultNodes` 10,000 structured values (nodes) across one result or parameter graph, `maxResultBytes` 1 MiB, `maxValueDepth` 8.
- **PostgreSQL column types:** `int8`/`bigint` (including `COUNT(*)`) is returned as a decimal `string` to preserve 64-bit precision (parse with `BigInt(...)` or `Number(...)` where safe); `numeric`/`decimal` as `string`; `date` as `YYYY-MM-DD` `string`; `timestamptz` as a JavaScript `Date`; `bytea` as `Uint8Array`; `json`/`jsonb` as parsed JS values.

### Private files (`OHMYHOST_STORAGE_*`)

Private storage requires `storage` configured in `ohmyhost.yaml` **and** deploying the target environment at least once (otherwise the bridge returns `403 gateway_not_enabled`).

```ts
import { createPrivateStorageClient } from "@ohmyhost/customer-runtime/storage";

const storage = createPrivateStorageClient({
  endpoint: env.OHMYHOST_STORAGE_GATEWAY_URL,
  key: env.OHMYHOST_STORAGE_KEY,
  projectId: env.OHMYHOST_PROJECT_ID,
  environmentId: env.OHMYHOST_ENVIRONMENT_ID,
  fetch: (request) => fetch(request, { redirect: "manual" }),
  capabilityFetch: (request) => fetch(request),
});
```

### Transactional mail (`OHMYHOST_MAIL_*`)

```ts
import { createTransactionalMailClient } from "@ohmyhost/customer-runtime/mail";

const mail = createTransactionalMailClient({
  endpoint: env.OHMYHOST_MAIL_GATEWAY_URL,
  key: env.OHMYHOST_MAIL_KEY,
  projectId: env.OHMYHOST_PROJECT_ID,
  fetch: (request) => fetch(request, { redirect: "manual" }),
});
```

Sending mail requires Paid access, credits, and a verified sender domain on the project. `mail.send()` returns a provider `messageId` (typically a UUID; absent when the state is `uncertain`); `ohmyhost mail messages list|get|retry` inspects **inbound received** mail by its inbound **ULID** (not outbound send ids).

### AI gateway (`OHMYHOST_AI_*`) and Browser PDF (`OHMYHOST_BROWSER_*`)

- **AI gateway:** works immediately from local dev on Paid workspaces with credits — even before enabling `ai` in `ohmyhost.yaml` and deploying. Local AI defaults to `OHMYHOST_AI_JURISDICTION=any` unless overridden to `eu` or locked by an active `eu` deployment. Every non-WebSocket AI gateway response carries `x-request-id` (a valid caller-supplied id is echoed; realtime `101` upgrades are skipped), and `GET /v1/models` returns `x-ohmyhost-ai-jurisdiction` (`eu` or `any`).
- **Browser PDF:** requires Paid access, credits, and an active deployment whose `ohmyhost.yaml` enables `browser.enabled: true` (otherwise the bridge returns `403 gateway_not_enabled`).

```ts
// AI chat completions (OpenAI-compatible)
const aiResponse = await fetch(`${env.OHMYHOST_AI_BASE_URL}/chat/completions`, {
  method: "POST",
  headers: {
    authorization: `Bearer ${env.OHMYHOST_AI_KEY}`,
    "content-type": "application/json",
  },
  body: JSON.stringify({
    model: selectedModelId,
    messages: [{ role: "user", content: "Summarize this status update." }],
  }),
});

// Browser PDF rendering (requires active deployment with browser.enabled: true)
const pdfResponse = await fetch(`${env.OHMYHOST_BROWSER_BASE_URL}/pdf`, {
  method: "POST",
  headers: {
    authorization: `Bearer ${env.OHMYHOST_BROWSER_KEY}`,
    "content-type": "application/json",
  },
  body: JSON.stringify({ html: "<html><body><h1>Invoice</h1></body></html>" }),
});
```

### Container jobs (`OHMYHOST_JOBS_*`) and Native Auth (`OHMYHOST_AUTH`)

- **Container jobs:** call `${env.OHMYHOST_JOBS_BASE_URL}/v1/...` with `Authorization: Bearer ${env.OHMYHOST_JOBS_TOKEN}`.
- **Native Auth:** pass `env.OHMYHOST_AUTH` to `createNativeAuthServer(env.OHMYHOST_AUTH)` and call `auth.getSession(request)` or `auth.requireUser(request)`.

## 5. Secrets separation (`.env.local` vs Secret Manager)

- **Platform bindings (`OHMYHOST_*`):** provided locally by `resolveOhMyHostEnv` and injected automatically by ohmyho.st on deployment. Never set `OHMYHOST_*` names in Secret Manager.
- **Application secrets (such as `STRIPE_SECRET_KEY`, `APP_AUTH_SECRET`, `APP_URL`):** stay in `.env.local` during local development and remain write-only in ohmyho.st Secret Manager when deployed (`ohmyhost secret set` or `ohmyhost secret form create`). They are never pulled down from the cloud; set them separately for Dev and Prod.

## 6. Local edge parity, crons, webhooks, and live logs

These CLI commands require `@amerged/ohmyhost-cli >= 0.1.87` (`--permissions` on `token create` requires `>= 0.1.91`) and read your local `ohmyhost.yaml` and `.env.local`:

```sh
# 1. Run local Worker bundle on 127.0.0.1 with Cloud Runtime Bridge + runtime.egress.allow enforced
ohmyhost dev --edge --port 8787 --json
# Optional flags: --directory PATH --entry PATH --environment dev|prod

# 2. Trigger one declared cron or all crons from functions.crons in ohmyhost.yaml
ohmyhost dev cron trigger --cron "*/15 * * * *" --url http://127.0.0.1:8787 --json
ohmyhost dev cron trigger --all --entry dist/worker.js --json

# 3. Replay a signed Standard Webhooks HMAC payload strictly to loopback (never prints secrets)
ohmyhost dev webhook replay --url http://127.0.0.1:3000/api/webhooks/mail \
  --kind mail --event email.received --secret-env OHMYHOST_MAIL_WEBHOOK_SECRET --json
ohmyhost dev webhook replay --url http://127.0.0.1:3000/api/webhooks/db \
  --kind database --event data.orders --secret-env OHMYHOST_DATABASE_WEBHOOK_SECRET --json

# 4. Follow live redacted runtime 5xx and uncaught exception logs from a deployed environment
ohmyhost deployment logs --project "$PROJECT_ID" --deployment "$DEPLOYMENT_ID" --follow --json
```

`ohmyhost dev --edge` enforces `runtime.egress.allow` locally: unlisted or retired hosts return HTTP 403 (`Outbound request blocked`), and redirects are not followed (HTTP 502), matching hosted Workers.

## 7. Troubleshooting local development

| Error or symptom                                                         | Cause                                                                                                                                                                     | Fix                                                                                                                                                      |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `runtime_env_invalid`                                                    | Missing/malformed `OHMYHOST_API_TOKEN`, non-ULID `OHMYHOST_PROJECT_ID`, invalid `OHMYHOST_ENVIRONMENT`, or called in browser code.                                        | Verify `.env.local` values, ensure `resolveOhMyHostEnv` only runs server-side, and confirm the dev server loaded `.env.local`.                           |
| `runtime_env_unavailable` (401 / 403 / 404)                              | Token lacks Owner `projects:write` or `runtime:use`, token belongs to another organization, or requested `dev` environment does not exist on a Free/Prod-only project.    | Create/verify an Owner token for the project's organization; omit `OHMYHOST_ENVIRONMENT` or set `OHMYHOST_ENVIRONMENT=prod` for Free/Prod-only projects. |
| `database_query_invalid`                                                 | `db.query({ text })` omitted `values: []`, exceeded a `DATABASE_CLIENT_LIMITS` cap (e.g. >100 parameters or >64 KiB JSON), or sent multiple statements / unsupported SQL. | Always pass `{ text: "...", values: [...] }` as a single statement within `DATABASE_CLIENT_LIMITS` (read the error detail for the exact limit).          |
| `database_unavailable` (underlying `project_database_unavailable`)       | Project has no provisioned database yet, database is waking after sleep, or Node `< 22` lacks global `WebSocket` for `withConnection`/`withRls`.                          | Run `database_migrate` / deploy once to provision the database, retry after cold wake (~5 s), and use Node 22+.                                          |
| `403 Outbound request blocked` / `502` redirect in `ohmyhost dev --edge` | Outbound server `fetch` targets an origin not listed in `runtime.egress.allow` (`403`) or received an unfollowed redirect (`502`).                                        | Add the exact final HTTPS origin to `runtime.egress.allow` in `ohmyhost.yaml` (platform gateways are allowed automatically).                             |
| `403 gateway_not_enabled`                                                | Capability (such as Browser PDF, Mail, or Storage) is not enabled in the target environment's active deployment.                                                          | Enable the capability in `ohmyhost.yaml` and deploy once (AI gateway works pre-deploy on Paid workspaces with credits).                                  |
| `402 paid_plan_required` / `insufficient_organization_credits`           | Local AI, Browser PDF, or Mail call on a Free workspace or depleted credit balance.                                                                                       | Enable Paid access and add credits in workspace billing.                                                                                                 |
