---
title: Stream a response
description: Send results while a handler runs, as server-sent events, and read them from an app.
related:
  - /http/serve-http-routes
  - /clients/call-lunas-from-typescript
  - /sdk/handler-spec
---

A handler that answers once makes its caller wait for the whole result. A long export, a model writing a reply or a task with progress has parts to show long before it ends.

A streaming handler sends each part as it has it. The caller receives server-sent events, the format a browser's `EventSource` reads.

## Write a streaming handler

Write the handler as an async generator, with `async function*`. Each value it yields is sent at once.

```ts luna/lunas/list.ts {10-15}
import { defineLuna, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  visibility: "public",
  key: { id: t.string() },
  schema: { items: table({ id: t.id(), text: t.string() }) },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => void ctx.db.items.insert({ text })),
    items: h({ route: "GET /lists/:id/items/live" }, async function* (ctx) {
      // One event for each item.
      for (const item of ctx.db.items.find({ orderBy: "id" })) {
        yield item;
      }
    }),
  }),
});
```

Called through its route, the handler answers `200` with `Content-Type: text/event-stream`. Each yielded value becomes one event, a `data:` line holding the value as JSON. A string goes as it is.

```bash
curl -N "<ROUTES_URL>/lists/groceries/items/live?key=$LUNA_KEY"
```

`<ROUTES_URL>` is the address [`luna status`](/cli/status) prints after `Routes at`. [Serve HTTP routes](/http/serve-http-routes) covers routes themselves.

## Name and number events

Yield `sse({ data, id, event, retry })` to set the event's fields, with `sse` imported from `luna`. `id` lets a client say where it stopped, `event` names the kind, and `retry` tells a browser how many milliseconds to wait before it reconnects.

```ts luna/lunas/list.ts
items: h({ route: "GET /lists/:id/items/live" }, async function* (ctx) {
  for (const item of ctx.db.items.find({ orderBy: "id" })) {
    yield sse({ id: item.id, event: "item", data: item });
  }
}),
```

For a list whose first item is `milk`, the first event is sent like this.

```text
event: item
id: 1
data: {"id":1,"text":"milk"}

```

## Go on from the last event

A browser's `EventSource` reconnects by itself, and sends the id of the last event it saw. Take the raw request with `args: t.request()` and read it as `req.lastEventId`, which is `null` on a first connection.

```ts luna/lunas/list.ts
items: h({ args: t.request(), route: "GET /lists/:id/items/live" }, async function* (ctx, req) {
  const after = Number(req.lastEventId ?? 0);
  for (const item of ctx.db.items.find({ where: { id: { gt: after } }, orderBy: "id" })) {
    yield sse({ id: item.id, event: "item", data: item });
  }
}),
```

## Set the status and headers

The first value a streaming handler yields may be a `Response` with a status from 200 to 299. Its status and headers become the stream's, and the events follow. A first `Response` with any other status is the whole answer, and no stream opens.

A streaming handler may also return a `Response` without yielding anything. The caller then gets that `Response` alone.

```ts luna/lunas/list.ts
items: h({ route: "GET /lists/:id/items/live" }, async function* (ctx) {
  if (ctx.db.items.count() === 0) return new Response(null, { status: 204 });
  yield new Response(null, { headers: { "cache-control": "no-store" } });
  for (const item of ctx.db.items.find({ orderBy: "id" })) yield item;
}),
```

## How a stream ends

A stream ends when the handler returns. If the handler throws after the stream opened, the last event is named `error`, and its data is the error as JSON with its `code`.

When the client goes away, Luna stops the handler at its next `yield`. `ctx.abortSignal` fires at that moment, so pass it on to work that should stop too, such as a `fetch`.

A stream stays open for at most 1 hour. Once it is open and the handler sends nothing, Luna sends a comment line every 15 seconds so that proxies keep the connection open.

## Read a stream from an app

`iterate` on a [`LunaHandle`](/sdk/luna-handle) calls a streaming handler by name and yields each event's data as it comes. It works with or without a route.

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

const client = createClient({ url: process.env.LUNA_URL!, key: process.env.LUNA_KEY });
const list = client.luna("List", "groceries");

for await (const item of list.iterate<{ id: number; text: string }>("items")) {
  console.log(item.text);
}
```

Breaking out of the loop stops the handler. An `error` event throws a `ConnectionError` with the error's code.

Over plain HTTP, call the handler at its usual address with `Accept: text/event-stream` to get the same events. A browser can open a `GET` route with `EventSource`, passing the publishable key as the `key` query parameter. Here `routesUrl` is the address `luna status` prints and `publishableKey` is your environment's publishable key.

```ts
const events = new EventSource(`${routesUrl}/lists/groceries/items/live?key=${publishableKey}`);
events.addEventListener("item", (e) => console.log(JSON.parse(e.data)));
```

## Next steps

- [Serve HTTP routes](/http/serve-http-routes) sets the path, the method and who may call.
- [Follow a stream from an app](/realtime/follow-a-stream-from-an-app) reads a luna's stored stream, which outlives any one call.
