---
title: Connect to an outside WebSocket
description: Open a WebSocket from a luna to another service, handle each message in a handler, and reopen it when it closes.
related:
  - /files-and-code/reach-the-internet
  - /background/schedule-a-handler
  - /develop/store-secrets
---

A luna's memory does not survive sleep, so a WebSocket kept in a variable is gone once the luna sleeps. `ctx.sockets` opens a WebSocket that Luna holds for the luna: it stays open while the luna sleeps, and each message from the other end runs one of the luna's handlers.

## Open a socket

`ctx.sockets.open` takes a `ws://` or `wss://` URL and the name of the handler that receives messages. It returns the socket, whose `id` names it from then on.

```ts luna/lunas/room.ts
import { defineLuna, t, table } from "luna";

const FEED_URL = "<FEED_URL>";

export const Room = defineLuna({
  name: "Room",
  key: { id: t.string() },
  schema: {
    messages: table({ id: t.id(), text: t.string() }),
  },
  handlers: (h) => ({
    follow: h({}, (ctx) => ctx.sockets.open(FEED_URL, { handler: "heard" }).id),
    heard: h({ args: { socket: t.string(), data: t.json() } }, (ctx, { data }) => {
      if (typeof data === "string") ctx.db.messages.insert({ text: data });
    }),
  }),
});
```

The socket opens once `follow` ends well. A handler that fails opens no socket and sends nothing on one.

## Handle each message

Each message from the other end is a call to the socket's handler, with two args.

| Arg | Holds |
| --- | --- |
| `socket` | The socket's id |
| `data` | A text message as a string, or a binary one as `{ base64 }` |

Messages run one at a time, in the order they arrived. A message to a sleeping luna wakes it.

:::warning
A message whose handler fails is not tried again. Store what arrives before you do anything that can fail, and do slow work later with `ctx.send`.
:::

## Send and close

`ctx.sockets.get(id)` returns an open socket, and `ctx.sockets.list()` returns them all. `send` sends a text message, and turns an object into JSON. `close` closes the socket.

```ts luna/lunas/room.ts
post: h({ args: { socket: t.string(), text: t.string() } }, (ctx, { socket, text }) => {
  return ctx.sockets.get(socket)?.send({ type: "post", text }) ?? false;
}),
stop: h({}, (ctx) => {
  for (const socket of ctx.sockets.list()) socket.close(1000, "done");
}),
```

`send` and `close` return `false` when the socket has already closed. What they do leaves once the handler ends well, as an open does. A message is at most 1 MiB, and a larger one fails `send` with `Invalid`.

## Reopen a socket that closed

`onClose` names a handler that runs once when the other end or the network closes the socket. It gets the socket's id, the close `code` and the `reason`. It does not run when the luna closes the socket itself.

```ts luna/lunas/room.ts
follow: h({}, (ctx) => ctx.sockets.open(FEED_URL, { handler: "heard", onClose: "closed" }).id),
closed: h({ args: { socket: t.string(), code: t.int(), reason: t.string() } }, (ctx, { code, reason }) => {
  console.log(`the feed closed: ${code} ${reason}`);
  ctx.schedule({ after: "10s", handler: "follow" });
}),
```

A socket that cannot connect also closes this way, with code 1006 and the reason in `reason`. Opening gives up after 10 seconds. [Schedule a handler](/background/schedule-a-handler) covers `ctx.schedule`.

## Send headers when opening

`headers` adds headers to the request that opens the socket, such as a token kept in a secret. The `Host` header comes from the URL and cannot be set.

```ts luna/lunas/room.ts
ctx.sockets.open(FEED_URL, {
  handler: "heard",
  headers: { authorization: `Bearer ${ctx.env.FEED_TOKEN}` },
});
```

[Store secrets](/develop/store-secrets) shows how to set `FEED_TOKEN`.

## Know what a luna may reach

- A URL that is not `ws://` or `wss://`, or is longer than 2,048 characters, fails `open` with `Invalid`. So does a handler name the luna type does not have.
- A luna has at most 64 sockets open at once. Opening one more fails with `Invalid`.
- Addresses Luna never lets a luna reach, such as loopback addresses, close the socket at once with code 1006.
- When any luna type in the app sets `internet: false`, every socket of the app closes at once with code 1006.

[Reach the internet](/files-and-code/reach-the-internet) explains which addresses are refused and what `internet: false` turns off.

## Next steps

- [Reach the internet](/files-and-code/reach-the-internet) covers `fetch` from a handler and outbound rules.
- [Call another luna](/lunas/call-another-luna) sends slow work on with `ctx.send`.
- [Open a connection](/realtime/open-a-connection) covers WebSockets that apps open to a luna.
