Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

connect

Open one raw connection to a luna from Node, to call it, follow queries, hear pushes and send messages to onMessage.

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

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)

PropType
basestring

The environment's URL, the LUNA_URL in .env.local.

Typestring
pathstring

The luna, as /<Type>/<key...>, such as /Room/lobby.

Typestring
opts?ConnectOptions

Credentials and parameters for the connection.

TypeConnectOptions

ConnectOptions

PropType
key?string

A publishable key, sent in the address as ?key=.

Typestring
headers?Record<string, string>

Extra request headers, such as Authorization: Bearer with a secret token. Node only.

TypeRecord<string, string>
params?Record<string, string>

Query parameters, which onBeforeConnect reads as request.query.

TypeRecord<string, string>

LunaSocket

PropType
openedPromise<void>

Resolves when the luna accepts the connection. Rejects with a ConnectionError when it refuses or the socket closes first.

TypePromise<void>
closedPromise<{ code: number; reason: string; refused?: Refusal }>

Resolves when the connection closes. refused holds the status and error of a refusal.

TypePromise<{ code: number; reason: string; refused?: Refusal }>
idstring | undefined

The connection's id, once open.

Typestring | undefined
authunknown

The identity the connection has, once open.

Typeunknown
call(handler, args, signal)Promise<R>

Calls a handler with the connection's identity. An AbortSignal stops the wait.

TypePromise<R>
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.

Type{ seq: number; done: Promise<R> }
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.

TypePromise<{ first: R; writes: number; stop(): Promise<void> }>
send(data)(data: unknown) => void

Sends a message to the luna's onMessage hook.

Type(data: unknown) => void
on(push, fn)() => void

Hears a push by name, or every push with "*". Returns a function that stops it.

Type() => void
close(code, reason)(code?: number, reason?: string) => void

Closes the connection. code is 1000 unless given.

Type(code?: number, reason?: string) => void

ConnectionError

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

PropType
codestring

The error's code: one of Luna's, such as Closed or Timeout, or the one the luna failed with.

Typestring
messagestring

What went wrong.

Typestring
dataunknown

What came with the error, such as a declared error's data.

Typeunknown
statusnumber | undefined

For a refused connection, the HTTP status. 403 when onBeforeConnect refused.

Typenumber | undefined

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

socket.send({ typing: true });

Connect with a secret token

import { connect } from "luna";

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

Follow a query

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

import { ConnectionError } from "luna";

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

Was this page helpful?