---
title: Call lunas from TypeScript
description: Create a client, call handlers with typed arguments, read indexes and handle failed calls from a web app or a Node.js program.
related:
  - /sdk/create-client
  - /sdk/luna-handle
  - /realtime/subscribe-to-a-query
---

An app needs to call handlers, wait for their answers and know when a call failed. The client in `luna/client` does this over one WebSocket that it opens when needed, shares between lunas and reopens after a drop.

## Create a client

[`createClient`](/sdk/create-client) takes the environment's URL and a publishable key, the `LUNA_URL` and `LUNA_KEY` that the CLI writes to `.env.local`. Create one client for the whole app.

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

export const client = createClient({
  url: process.env.LUNA_URL!,
  key: process.env.LUNA_KEY,
});
```

The client runs in browsers and in Node.js 22.18 or later. A browser app reads the URL and key the way its bundler exposes them, as [Use Luna with React](/clients/use-luna-with-react) shows. Every option except `url` can be left out.

| Option | Does |
| --- | --- |
| `url` | The environment's URL |
| `key` | A publishable key |
| `token` | A secret token instead of a key, in Node.js only |
| `headers` | Extra request headers, in Node.js only |
| `params` | Query parameters for each new connection, for `onBeforeConnect` to read. Asked again on every reconnect |
| `callTimeoutMs` | How long a call may take, waiting to connect included. 30 seconds by default |
| `keepAliveMs` | How long a query nobody watches stays live and cached. 10 seconds by default |
| `settleMs` | How long a confirmed optimistic write stays shown over queries of other lunas. 1 second by default |
| `multiplex` | One WebSocket for all lunas, the default, or `false` for one each |
| `store`, `optimistic` | Keep results and queued writes between runs, as [Work offline](/clients/work-offline) shows |

## Call a handler

`client.luna(type, ...key)` returns a [`LunaHandle`](/sdk/luna-handle) for one luna. `mutate` calls a handler and resolves with what it returns. `read` calls a handler once without following it, which suits a query handler.

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

const list = client.luna<typeof List>("List", "groceries");

await list.mutate("add", { text: "milk" });
const items = await list.read("all");
console.log(items.map((item) => item.text));
```

With `typeof List`, TypeScript checks each handler name, argument and result. The import is a type import, so the app never bundles the luna's code. [Generate a typed client](/clients/generate-a-typed-client) covers the other languages.

Pass the key's fields in the order the luna type declares them, such as `client.luna("Card", boardId, cardId)`. Calls to one luna go in order over its connection, so a `read` sent after a `mutate` sees that write.

## Follow a query

`query` returns a live query instead of one answer. `subscribe` hears each new result, and `get` returns the latest state.

```ts app/groceries.ts
const all = list.query("all");
const stop = all.subscribe(() => {
  const { data } = all.get();
  if (data) console.log(data.map((item) => item.text));
});
```

[Subscribe to a query](/realtime/subscribe-to-a-query) explains what brings a new result and the states a query goes through.

## Show a write before it is confirmed

`mutate` takes `MutateOptions` as its third argument. `optimistic` changes what live queries show while the call is on its way, and `timeoutMs` sets this call's time limit.

```ts app/groceries.ts {5-6}
await list.mutate(
  "add",
  { text: "eggs" },
  {
    optimistic: (local) => local.update(all, (items) => [...items, { id: -1, text: "eggs" }]),
    timeoutMs: 5_000,
  },
);
```

The update is laid over the latest confirmed result and shows at once. It stays until a live result that includes the write arrives, so the item never shows twice. If the call fails, the update is removed and `mutate` throws. `local.update` changes only a query that has loaded.

## Read a handler's HTTP response

A handler that answers with a `Response`, such as one behind an [HTTP route](/http/serve-http-routes), can be called with `response`. It resolves with the status, the headers and the body.

```ts app/groceries.ts
const res = await client.luna("List", "groceries").response("export", {});
if (res.status === 200) console.log(res.headers.get("content-type"), res.body);
```

`mutate` and `read` give such a handler's body alone, and throw an `HttpError` for a status of 400 or above. A handler that yields values as it runs is read with `iterate`, as [Stream a response](/http/stream-a-response) shows.

## Read an index

`client.index(name, partition)` returns an [`IndexHandle`](/sdk/index-handle) for one partition of an index. Its `find`, `count`, `groupBy`, `search` and `nearest` each return a live query.

```ts app/search.ts
import type { BoardSearch } from "../luna/lunas/board-search.ts";
import { client } from "./luna.ts";

const search = client.index<typeof BoardSearch>("BoardSearch", "b1");
const hits = search.search("mil", { prefix: true, limit: 20 });
hits.subscribe(() => {
  for (const { row, score } of hits.get().data ?? []) console.log(row.text, score);
});
```

An app can read an index only if the index has an `onBeforeConnect` that lets it in. [Query across lunas](/data/query-across-lunas) shows how to define one.

## Handle a failed call

A failed call rejects with a [`ConnectionError`](/sdk/connect). Its `code` is a declared error's code from [`ctx.fail`](/lunas/return-errors), or one of Luna's own codes, and `data` holds the error's data.

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

try {
  await list.mutate("add", { text: "milk" });
} catch (e) {
  if (!(e instanceof ConnectionError)) throw e;
  if (e.code === "Timeout") console.log("No answer yet. The item may still be added.");
  else console.log(e.code, e.message, e.data);
}
```

| `code` | The call |
| --- | --- |
| A declared code | Failed with `ctx.fail` in the handler |
| `Timeout` | Had no answer within its time limit, and may still run |
| `Closed` | Lost its connection before the answer, and may or may not have run |
| The luna's own code | Was refused by `onBeforeConnect`. `status` is 403 |
| Another of Luna's codes | Failed in Luna, as [Errors](/errors) lists |

## Call from your own server

In Node.js, pass a secret token as `token` instead of a key. It reaches private luna types too, and travels in a header, never in the URL.

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

const client = createClient({
  url: process.env.LUNA_URL!,
  token: process.env.LUNA_SECRET_TOKEN,
});
```

:::warning
A secret token reaches every luna type of the environment. Keep it on your servers and never ship it in an app.
:::

## Close the client

`client.close()` closes every connection, and the client cannot be used after. Call it when a script or a server shuts down.

## Next steps

- [Use Luna with React](/clients/use-luna-with-react) wraps the same handles in hooks.
- [Work offline](/clients/work-offline) keeps results and writes on the device.
- [Keys and tokens](/concepts/keys-and-tokens) explains publishable keys and secret tokens.
