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

> ## Agent Instructions
> For account actions, read https://ohmyho.st/skills/ohmyhost-get-started/SKILL.md and use the authenticated ohmyho.st CLI, local product MCP or supported remote OAuth MCP. Read the current project source binding before choosing GitHub or managed versions. Mintlify search only reads documentation. Preserve the customer’s selected project, environment and authentication provider; keep private application values in the one-hour secret link or local stdin flow.

# Local development

> Develop locally with pnpm dev, Vitest, and Node scripts directly against your hosted Dev or Prod database, private files, mail, AI gateway, Browser PDF, container jobs, and Native Auth.

Develop and test locally with your normal framework dev server (`pnpm dev`), Vitest, or Node scripts directly against your real hosted ohmyho.st **Dev** (or **Prod**) resources — without installing or maintaining local PostgreSQL, R2, or Resend emulators.

Your server code calls `resolveOhMyHostEnv(workerEnv)` once:

* **In Cloudflare Workers (hosted Dev / Prod):** returns `workerEnv` untouched with zero network overhead.
* **Locally (`pnpm dev`, Vitest, scripts):** returns the exact same `env` bindings backed by the Owner-authenticated Cloud Runtime Bridge on `https://app.ohmyho.st`.

> [!NOTE]
>
> Prefer letting your coding agent set this up? The [`ohmyhost-build-portable-app`](https://ohmyho.st/skills/ohmyhost-build-portable-app/SKILL.md) Skill includes the matching [local development reference](https://ohmyho.st/skills/ohmyhost-build-portable-app/references/local-development.md) so agents wire `.env.local`, `resolveOhMyHostEnv`, and `ohmyhost dev` automatically.

## 1. Create an Owner API token and configure `.env.local`

Local cloud development requires an **Owner** API token with `projects:write` (or the narrower Owner-only `runtime:use` permission) and your project ULID.

1. Find your organization ULID and project ULID:

```sh theme={null}
ohmyhost whoami --json
ohmyhost project list --json
```

2. Create an Owner API token in the portal at [app.ohmyho.st/tokens](https://app.ohmyho.st/tokens) (default full permission set) or, for least privilege, with the CLI (in a shell where `OHMYHOST_TOKEN` is unset). Pass `--permissions runtime:use` (CLI `>= 0.1.91`) so the local token can only reach the Cloud Runtime Bridge and cannot modify projects or billing:

```sh theme={null}
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 variable). Local runtime resolution reads `OHMYHOST_API_TOKEN` so your interactive CLI login and your application's local runtime bridge stay cleanly separated.

3. Add the token and project ULID to `.env.local` in your application root (and verify `.env.local` is in `.gitignore`):

```bash theme={null}
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...     # explicit environment ULID to skip initial /runtime/resolve
```

### Environment variable reference

| Variable | Required | Default | Description |
| - | - | - | - |
| `OHMYHOST_API_TOKEN` | Yes | — | Owner API token with `projects:write` or `runtime:use`. Keep out of Git and browser bundles. |
| `OHMYHOST_PROJECT_ID` | Yes | — | Target project ULID from `ohmyhost project list --json`. |
| `OHMYHOST_ENVIRONMENT` | No | `dev` if present, else `prod` | Targets `dev` or `prod`. Free workspaces and Prod-only projects default to `prod`. |
| `OHMYHOST_AI_JURISDICTION` | No | `any` | Selects `any` or `eu` for local AI calls. If the active deployment is locked to `eu`, `eu` remains enforced. |
| `OHMYHOST_ENVIRONMENT_ID` | No | Resolved automatically | Optional explicit environment ULID; bypasses the cached `GET .../runtime/resolve` call. |

### Free vs Paid environment targeting

| Workspace / project setup | Default when `OHMYHOST_ENVIRONMENT` is omitted | Notes |
| - | - | - |
| Paid workspace with Dev + Prod | `dev` | Set `OHMYHOST_ENVIRONMENT=prod` only when you deliberately want to target Prod. |
| Free workspace or Prod-only project | `prod` | Local database and file writes modify real Prod data. |
| Shared Dev/Prod data mode | `dev` (shares DB with `prod`) | Database writes affect both environments. Use [isolated data](https://docs.ohmyho.st/environments.md#change-data-assignments) to keep Dev and Prod separate. |

## 2. Install the runtime package alias

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

```json theme={null}
{
  "dependencies": {
    "@ohmyhost/customer-runtime": "npm:@amerged/ohmyhost-runtime@0.1.91"
  }
}
```

Both `@ohmyhost/customer-runtime` (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 in server code

Call `resolveOhMyHostEnv(workerEnv)` in server-only code (calling it in a browser throws `runtime_env_invalid`).

### 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 theme={null}
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 Workers, Vitest, and Node scripts

Pass your runtime `env` when available, or omit it (`undefined`) in local scripts and tests:

```ts theme={null}
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);
  const db = createPrivateDatabaseClient(env.OHMYHOST_DATABASE);
  return { env, db };
}
```

## 4. Use hosted capabilities locally

Every binding returned by `resolveOhMyHostEnv` matches the deployed Cloudflare Worker shape:

### PostgreSQL (`OHMYHOST_DATABASE`)

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

```ts theme={null}
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; requires Node 22+)
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 (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: [] });
});
```

For `withConnection` and `withRls`, the runtime exchanges your bearer token over HTTPS for a single-use 30-second HMAC WebSocket ticket so your API token never appears in a WebSocket URL. See [Postgres queries, writes and compute](https://docs.ohmyho.st/database.md) and [Row-level security](https://docs.ohmyho.st/row-level-security.md) for query limits and Kysely usage.

#### Database client limits (`DATABASE_CLIENT_LIMITS`) and PostgreSQL column types

Import `DATABASE_CLIENT_LIMITS` from `@ohmyhost/customer-runtime/database` to mirror the exact limits enforced both locally and hosted:

| Limit | Value | Notes |
| - | - | - |
| `maxQueryBytes` | `65,536` (64 KiB) | Maximum UTF-8 byte length of a single SQL statement. |
| `maxParameters` | `100` | Maximum positional parameters (`$1..$100`) per statement. Batch large writes or pass array parameters with `UNNEST`. |
| `maxParameterBytes` | `1,048,576` (1 MiB) | Aggregate parameter payload budget across a query or `transaction()`. |
| `maxJsonParameterBytes` | `65,536` (64 KiB) | Maximum estimated size of a single object or array parameter (including `UNNEST` arrays): string and key bytes, 8 per number, 24 per date. |
| `maxKeyBytes` | `128` | Maximum UTF-8 byte length of a JSON object key. |
| `maxTransactionQueries` | `25` | Maximum statements in one `db.transaction([...])` call. |
| `maxResultRows` | `1,000` | Maximum rows returned per statement. |
| `maxResultNodes` | `10,000` | Maximum number of structured values (nodes) in a result or parameter graph. |
| `maxResultBytes` | `1,048,576` (1 MiB) | Maximum serialized result size per statement. |
| `maxValueDepth` | `8` | Maximum nesting depth for structured JSON parameters and rows. |

**PostgreSQL column type mapping:**

* `int8` / `bigint` (including `COUNT(*)`): returned as a decimal `string` to preserve 64-bit precision (parse with `BigInt(...)` or `Number(...)` where safe).
* `numeric` / `decimal`: returned as `string`.
* `date`: returned as `YYYY-MM-DD` `string`.
* `timestamptz`: returned as a JavaScript `Date`.
* `bytea`: returned as `Uint8Array`.
* `json` / `jsonb`: returned as parsed JavaScript values.

### Private files (`OHMYHOST_STORAGE_*`)

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

```ts theme={null}
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),
});
```

See [Files](https://docs.ohmyho.st/files.md) for upload, read, and delete methods.

### Transactional mail (`OHMYHOST_MAIL_*`)

```ts theme={null}
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" }),
});
```

Requires Paid access, credits, and a verified sender domain on the project. `mail.send()` returns `messageId`, an outbound provider identifier (typically a UUID; absent when `state` is `uncertain`); `ohmyhost mail messages list|get|retry` inspects **inbound received** mail using its inbound **ULID**, not outbound send identifiers. See [Email](https://docs.ohmyho.st/email.md).

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

* **AI gateway:** works immediately from local development on Paid workspaces with credits — even before enabling `ai` in `ohmyhost.yaml` and deploying. Local AI defaults to `any` unless you set `OHMYHOST_AI_JURISDICTION=eu` or the active deployment is locked to `eu`. Every non-WebSocket AI response carries `x-request-id`, and `GET /v1/models` includes `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 theme={null}
// OpenAI-compatible AI gateway (works pre-deploy on Paid workspaces with credits)
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>" }),
});
```

See [AI gateway](https://docs.ohmyho.st/ai.md) and [Browser PDF](https://docs.ohmyho.st/browser-pdf.md) for supported routes, limits, and pricing.

### 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}`. See [Container jobs](https://docs.ohmyho.st/container-jobs.md).
* **Native Auth:** pass `env.OHMYHOST_AUTH` to `createNativeAuthServer(env.OHMYHOST_AUTH)` and use `auth.getSession(request)` or `auth.requireUser(request)`. See [Application authentication](https://docs.ohmyho.st/application-auth.md).

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

* **Platform bindings (`OHMYHOST_*`):** provided locally by `resolveOhMyHostEnv` and injected automatically by ohmyho.st when deployed. Never add `OHMYHOST_*` names to the platform Secret Manager.
* **Third-party and application secrets (such as `STRIPE_SECRET_KEY`, `APP_AUTH_SECRET`, `APP_URL`):** stay in `.env.local` during local development and remain write-only in the platform [Secret Manager](https://docs.ohmyho.st/secrets.md) when deployed. ohmyho.st never pulls secret values back down to your laptop; upload them separately for Dev and Prod using `ohmyhost secret set` or `ohmyhost secret form create`.

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

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

### Run your Worker locally with egress parity (`ohmyhost dev --edge`)

```sh theme={null}
ohmyhost dev --edge --port 8787 --json
# Optional flags: --directory PATH --entry PATH --environment dev|prod
```

Runs your local Worker bundle on `127.0.0.1` with the Cloud Runtime Bridge bindings and enforces `runtime.egress.allow` from `ohmyhost.yaml` — blocking unlisted or retired hosts with HTTP 403 (`Outbound request blocked`) and refusing redirects with HTTP 502, matching hosted Workers.

### Trigger scheduled cron handlers locally (`ohmyhost dev cron trigger`)

```sh theme={null}
# Against a running `ohmyhost dev --edge` server:
ohmyhost dev cron trigger --cron "*/15 * * * *" --url http://127.0.0.1:8787 --json

# Or invoke all declared schedules directly against a built Worker module:
ohmyhost dev cron trigger --all --entry dist/worker.js --json
```

Validates every requested cron expression against `functions.crons` in `ohmyhost.yaml` before dispatching `scheduled(controller, env, ctx)`.

### Replay signed webhooks locally (`ohmyhost dev webhook replay`)

```sh theme={null}
# Inbound mail webhook
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

# Database watch webhook (or pass --payload-file PATH and/or --stdin for the secret)
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
```

Builds and signs an authentic Standard Webhooks HMAC payload (`webhook-id`, `webhook-timestamp`, `webhook-signature`) and delivers it strictly to loopback (`127.0.0.1`, `localhost`, `[::1]`) without printing secrets.

### Follow live hosted runtime logs (`ohmyhost deployment logs --follow`)

```sh theme={null}
ohmyhost deployment logs --project "$PROJECT_ID" --deployment "$DEPLOYMENT_ID" --follow --json
```

Polls redacted runtime `5xx` and uncaught exception diagnostics (`route`, `status_code`, `request_id`, `duration_ms`, and safe `exception_class` — never exception messages, query strings, or secrets) until interrupted.

## 7. Troubleshooting

| Error or symptom | Cause | Fix |
| - | - | - |
| `runtime_env_invalid` | Missing or malformed `OHMYHOST_API_TOKEN`, non-ULID `OHMYHOST_PROJECT_ID`, invalid `OHMYHOST_ENVIRONMENT`, or called in browser code. | Check `.env.local`, confirm your dev server loads `.env.local`, and ensure `resolveOhMyHostEnv` only runs server-side. |
| `runtime_env_unavailable` (401 / 403 / 404) | Token lacks Owner `projects:write` or `runtime:use`, belongs to a different organization, or `OHMYHOST_ENVIRONMENT=dev` was requested on a Free/Prod-only project. | Create or select an Owner token for the project's organization; omit `OHMYHOST_ENVIRONMENT` or set `OHMYHOST_ENVIRONMENT=prod` for Prod-only projects. |
| `database_query_invalid` | `db.query({ text })` omitted `values: []`, sent multiple statements, or exceeded SQL/parameter limits. | Always pass `{ text: "...", values: [...] }` as a single SQL statement. |
| `database_unavailable` (underlying `project_database_unavailable`) | The target environment has no database provisioned yet, the database is waking from sleep, or Node `< 22` lacks global `WebSocket` for `withConnection`/`withRls`. | Provision the database via `ohmyhost database migrate` or a first deploy, wait a few seconds for cold wake, and run 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 gateway origins 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` or `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](https://docs.ohmyho.st/billing.md). |

[CLI](https://docs.ohmyho.st/cli.md) · [Postgres](https://docs.ohmyho.st/database.md) · [Runtime secrets](https://docs.ohmyho.st/secrets.md) · [Troubleshooting](https://docs.ohmyho.st/troubleshooting.md).


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