---
title: createClient
description: Make the client an app uses to call lunas, follow live queries and queue writes, from luna/client.
related:
  - /clients/call-lunas-from-typescript
  - /sdk/luna-handle
  - /clients/work-offline
---

`createClient` makes a `LunaClient`, which connects an app to the lunas of one environment.

```ts app/luna.ts
import { createClient } from "luna/client";
import type { List } from "../luna/lunas/list.ts";

const client = createClient({ url: "<LUNA_URL>", key: "<LUNA_KEY>" });

const list = client.luna<typeof List>("List", "groceries");
await list.mutate("add", { text: "milk" });
```

## Reference

### createClient(options)

Returns a `LunaClient`. It takes one object of `ClientOptions`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `url` | `string` | - | The environment's URL, the LUNA_URL in .env.local. |
| `key?` | `string` | - | A publishable key. It reaches public luna types only. |
| `token?` | `string` | - | A secret token, sent as Authorization: Bearer. It reaches private luna types too. Node only, never in an app. |
| `headers?` | `Record<string, string>` | - | Extra request headers. Node only. |
| `params?` | `() => Record<string, string> \| Promise<Record<string, string>>` | - | Query parameters for each new connection, which onBeforeConnect reads as request.query. Asked again on every reconnect. |
| `keepAliveMs?` | `number` | `10000` | How long a query nobody watches stays live and cached, and how long an unused connection stays open. |
| `settleMs?` | `number` | `1000` | How long a confirmed write stays laid over the queries of other lunas. Queries of the write's own luna get four times as long. |
| `callTimeoutMs?` | `number` | `30000` | How long a call may take, including the wait to connect. |
| `multiplex?` | `boolean` | `true` | One WebSocket for all of the client's lunas. With false, one each. |
| `store?` | `ClientStore` | - | Where query results and queued writes are kept between runs. Use one per account. |
| `optimistic?` | `Record<string, QueuedOptimistic>` | - | Optimistic updates for queued writes, by name. |

### LunaClient

The methods an app calls.

| Prop | Type | Default | Description |
| - | - | - | - |
| `luna(type, ...key)?` | `(type: string, ...key: (string \| number)[]) => LunaHandle` | - | One luna, by its type and its key values in the order the type declares them. See LunaHandle. |
| `index(name, partition)?` | `(name: string, partition: string \| number) => IndexHandle` | - | One partition of an index, read live. See IndexHandle. |
| `writes()?` | `() => readonly QueuedWrite[]` | - | The queued writes that wait or failed, oldest first. |
| `subscribeWrites(fn)?` | `(fn: () => void) => () => void` | - | Hears every change to the queue. Returns a function that stops it. |
| `resumeWrites()?` | `() => void` | - | Sends the queue again after it stopped for a sign-in that ran out. |
| `retryWrite(id)?` | `(id: string) => void` | - | Puts a failed write back in the queue. |
| `discardWrite(id)?` | `(id: string) => void` | - | Drops a failed write from the queue and the store. |
| `wipe()?` | `() => Promise<void>` | - | Empties the store and the queue. The promises of queued writes reject with Closed. |
| `close()?` | `() => void` | - | Closes every connection. The client cannot be used after. |
| `options?` | `ClientOptions` | - | The options the client was made with. |

### ClientStore

Text kept by key. Each method may return its value or a promise of it.

| Prop | Type | Default | Description |
| - | - | - | - |
| `get(key)` | `(key: string) => string \| undefined` | - | The text saved at a key. |
| `set(key, value)` | `(key: string, value: string) => void` | - | Saves text at a key. |
| `delete(key)` | `(key: string) => void` | - | Removes a key. |
| `keys(prefix)` | `(prefix: string) => string[]` | - | Every key that starts with prefix. |

### webStore(prefix, storage)

Returns a `ClientStore` over `localStorage`, or any object shaped like the browser's `Storage`. It saves each key as `<prefix>:<key>`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `prefix` | `string` | - | Keeps this store's keys apart from others. Give each account its own. |
| `storage?` | `Storage` | `globalThis.localStorage` | Where the text goes. |

### QueuedWrite

| Prop | Type | Default | Description |
| - | - | - | - |
| `id` | `string` | - | The write's id. It is also the idempotency key the write is sent with. |
| `path` | `string` | - | The luna it is for, such as /List/groceries. |
| `handler` | `string` | - | The handler it calls. |
| `args` | `Record<string, unknown>` | - | The handler's arguments. |
| `status` | `"pending" \| "failed"` | - | Whether it waits to be sent or failed. |
| `error?` | `{ code: string; message: string }` | - | Why it failed. |

### QueuedOptimistic

```ts
type QueuedOptimistic = (
  local: LocalStore,
  write: { luna: LunaHandle; args: Record<string, unknown> },
) => void;
```

An optimistic update for a queued write, given by name in `options.optimistic`. A write queued in an earlier run keeps only that name, so the functions are given when the client starts. `LocalStore` is on the [LunaHandle](/sdk/luna-handle) page.

## Good to know

- `mutate`, `read`, live queries and pushes travel over a WebSocket, while `iterate` and `stream` use HTTP. With `multiplex`, one socket carries every luna, and each luna still runs its own `onBeforeConnect`.
- A browser cannot set headers on a WebSocket, so `token` and `headers` work in Node only. The publishable key goes in the address as `?key=`.
- A dropped connection reconnects on its own. The wait grows with each failed try, from 200 ms up to 15 s.
- A luna that closes the connection itself, with code 1000 or 4000 to 4999, is not reconnected. The next use of that luna opens a new connection, and `params` is asked again.
- A refused connection fails the calls that wait for it with the luna's own error code. Live queries keep trying after a refusal with status 408, 429, or 500 and above.
- `enqueue` throws `Invalid` when the client has no `store`, or when the optimistic update it names was not given here.
- After `close()`, every call throws a `ConnectionError` with code `Closed`.

## Examples

### Call a private luna from your server

A secret token reaches private luna types. Keep it on a server.

```ts app/server.ts
import { createClient } from "luna/client";

const client = createClient({
  url: "<LUNA_URL>",
  token: "<SECRET_TOKEN>",
});
```

### Send your app's sign-in with each connection

`params` runs before each connection opens, so a token that was refreshed reaches `onBeforeConnect`.

```ts app/luna.ts
import { createClient } from "luna/client";

const client = createClient({
  url: "<LUNA_URL>",
  key: "<LUNA_KEY>",
  params: () => ({ session: localStorage.getItem("session") ?? "" }),
});
```

### Keep results and writes between runs

With a `store`, saved results show as stale until live ones arrive, and queued writes survive a restart.

```ts app/luna.ts
import { createClient, webStore } from "luna/client";

type Item = { id: number; text: string };

const client = createClient({
  url: "<LUNA_URL>",
  key: "<LUNA_KEY>",
  store: webStore("account-42"),
  optimistic: {
    addItem: (local, { luna, args }) =>
      local.update(luna.query("all"), (items: Item[]) => [
        ...items,
        { id: -1, text: String(args.text) },
      ]),
  },
});

client.luna("List", "groceries").enqueue("add", { text: "milk" }, { optimistic: "addItem" });
```

### Show writes that failed

```ts app/queue.ts
import type { LunaClient } from "luna/client";

export function watchQueue(client: LunaClient) {
  return client.subscribeWrites(() => {
    for (const w of client.writes()) {
      if (w.status === "failed") console.warn(w.handler, w.error?.message);
    }
  });
}
```

Call `client.retryWrite(id)` to send a failed write again, or `client.discardWrite(id)` to drop it.

### Clear an account's data on sign-out

```ts app/sign-out.ts
import type { LunaClient } from "luna/client";

export async function signOut(client: LunaClient) {
  await client.wipe();
  client.close();
}
```
