---
title: connect
description: Open one raw connection to a luna from Node, to call it, follow queries, hear pushes and send messages to onMessage.
related:
  - /realtime/open-a-connection
  - /sdk/create-client
  - /sdk/luna-handle
---

`connect` opens one WebSocket to one luna and returns a `LunaSocket`. It comes from `luna`, the SDK's main entry, not from `luna/client`.

```ts app/bot.ts
import { connect } from "luna";

const socket = connect("<LUNA_URL>", "/Room/lobby", { key: "<LUNA_KEY>" });
await socket.opened;

socket.on<{ text: string }>("said", (m) => console.log(m.text));
await socket.call("say", { text: "hello" });
socket.close();
```

## Reference

### connect(base, path, opts)

| Prop | Type | Default | Description |
| - | - | - | - |
| `base` | `string` | - | The environment's URL, the LUNA_URL in .env.local. |
| `path` | `string` | - | The luna, as /<Type>/<key...>, such as /Room/lobby. |
| `opts?` | `ConnectOptions` | - | Credentials and parameters for the connection. |

### ConnectOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `key?` | `string` | - | A publishable key, sent in the address as ?key=. |
| `headers?` | `Record<string, string>` | - | Extra request headers, such as Authorization: Bearer with a secret token. Node only. |
| `params?` | `Record<string, string>` | - | Query parameters, which onBeforeConnect reads as request.query. |

### LunaSocket

| Prop | Type | Default | Description |
| - | - | - | - |
| `opened` | `Promise<void>` | - | Resolves when the luna accepts the connection. Rejects with a ConnectionError when it refuses or the socket closes first. |
| `closed` | `Promise<{ code: number; reason: string; refused?: Refusal }>` | - | Resolves when the connection closes. refused holds the status and error of a refusal. |
| `id` | `string \| undefined` | - | The connection's id, once open. |
| `auth` | `unknown` | - | The identity the connection has, once open. |
| `call(handler, args, signal)` | `Promise<R>` | - | Calls a handler with the connection's identity. An AbortSignal stops the wait. |
| `write(handler, args, idempotencyKey, signal)` | `{ seq: number; done: Promise<R> }` | - | Calls a handler as one of this connection's writes, numbered by seq, run one at a time in order. |
| `subscribe(handler, args, onUpdate)` | `Promise<{ first: R; writes: number; stop(): Promise<void> }>` | - | Makes a live query. Resolves with the first result, and onUpdate hears each later one. |
| `send(data)` | `(data: unknown) => void` | - | Sends a message to the luna's onMessage hook. |
| `on(push, fn)` | `() => void` | - | Hears a push by name, or every push with "*". Returns a function that stops it. |
| `close(code, reason)` | `(code?: number, reason?: string) => void` | - | Closes the connection. code is 1000 unless given. |

### ConnectionError

The error `LunaSocket` and the app client throw. `luna/client` exports it too.

| Prop | Type | Default | Description |
| - | - | - | - |
| `code` | `string` | - | The error's code: one of Luna's, such as Closed or Timeout, or the one the luna failed with. |
| `message` | `string` | - | What went wrong. |
| `data` | `unknown` | - | What came with the error, such as a declared error's data. |
| `status` | `number \| undefined` | - | For a refused connection, the HTTP status. 403 when onBeforeConnect refused. |

## Good to know

- A `LunaSocket` does not reconnect. When it closes, every call still waiting rejects with `Closed`, and you open a new one.
- When `onBeforeConnect` refuses, the socket opens, says why and closes with code 4000 plus the HTTP status. `opened` rejects with the luna's own code.
- An `onUpdate` from `subscribe` carries `result` or `error`, and `writes`: how many of this connection's writes the result includes. An update with neither `result` nor `error` only moves `writes` on.
- `on("*", fn)` gives `fn` each push as `{ event, data }`. `on("error", fn)` hears errors that belong to no call.
- `luna`, the main entry, also imports Node's own modules. Run `connect` in Node 22.18 or later, such as in a script or on your server.

## Examples

### Choose connect or createClient

| Need | Use |
| --- | --- |
| Live queries shared across a view, optimistic writes, reconnecting, offline writes | `createClient` |
| Raw messages to `onMessage` | `connect` |
| The connection's own `id` and `auth` | `connect` |
| One connection that ends when you close it | `connect` |

### Send messages to onMessage

```ts app/bot.ts
socket.send({ typing: true });
```

### Connect with a secret token

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

const socket = connect("<LUNA_URL>", "/Room/lobby", {
  headers: { authorization: "Bearer <SECRET_TOKEN>" },
});
```

### Follow a query

```ts app/bot.ts
const sub = await socket.subscribe<string[]>("recent", {}, (u) => {
  if ("result" in u) console.log(u.result);
});
console.log(sub.first);
await sub.stop();
```

### Find out why a connection was refused

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

try {
  await socket.opened;
} catch (e) {
  if (e instanceof ConnectionError) console.log(e.status, e.code, e.message);
}
```
