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)
basestring
The environment's URL, the LUNA_URL in .env.local.
stringpathstring
The luna, as /<Type>/<key...>, such as /Room/lobby.
stringopts?ConnectOptions
Credentials and parameters for the connection.
ConnectOptionsConnectOptions
key?string
A publishable key, sent in the address as ?key=.
stringheaders?Record<string, string>
Extra request headers, such as Authorization: Bearer with a secret token. Node only.
Record<string, string>params?Record<string, string>
Query parameters, which onBeforeConnect reads as request.query.
Record<string, string>LunaSocket
openedPromise<void>
Resolves when the luna accepts the connection. Rejects with a ConnectionError when it refuses or the socket closes first.
Promise<void>closedPromise<{ code: number; reason: string; refused?: Refusal }>
Resolves when the connection closes. refused holds the status and error of a refusal.
Promise<{ code: number; reason: string; refused?: Refusal }>idstring | undefined
The connection's id, once open.
string | undefinedauthunknown
The identity the connection has, once open.
unknowncall(handler, args, signal)Promise<R>
Calls a handler with the connection's identity. An AbortSignal stops the wait.
Promise<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.
{ 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.
Promise<{ first: R; writes: number; stop(): Promise<void> }>send(data)(data: unknown) => void
Sends a message to the luna's onMessage hook.
(data: unknown) => voidon(push, fn)() => void
Hears a push by name, or every push with "*". Returns a function that stops it.
() => voidclose(code, reason)(code?: number, reason?: string) => void
Closes the connection. code is 1000 unless given.
(code?: number, reason?: string) => voidConnectionError
The error LunaSocket and the app client throw. luna/client exports it too.
codestring
The error's code: one of Luna's, such as Closed or Timeout, or the one the luna failed with.
stringmessagestring
What went wrong.
stringdataunknown
What came with the error, such as a declared error's data.
unknownstatusnumber | undefined
For a refused connection, the HTTP status. 403 when onBeforeConnect refused.
number | undefinedGood to know
- A
LunaSocketdoes not reconnect. When it closes, every call still waiting rejects withClosed, and you open a new one. - When
onBeforeConnectrefuses, the socket opens, says why and closes with code 4000 plus the HTTP status.openedrejects with the luna’s own code. - An
onUpdatefromsubscribecarriesresultorerror, andwrites: how many of this connection’s writes the result includes. An update with neitherresultnorerroronly moveswriteson. on("*", fn)givesfneach push as{ event, data }.on("error", fn)hears errors that belong to no call.luna, the main entry, also imports Node’s own modules. Runconnectin 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);
}