---
title: Server-Sent Events
description: Stream typed events from a route and read them on the client.
---

A handler that returns an async iterable streams Server-Sent Events. Each
yielded value is one event, sent as JSON.

## Send Events

```ts
import { route, sse } from "@rest-rpc/server";

const notifications = route
	.get("/notifications")
	.response(sse(z.object({ postId: z.string(), message: z.string() })))
	.handler(async function* () {
		yield { postId: "post_1", message: "Ada liked your post" };
		yield { postId: "post_1", message: "Grace commented on your post" };
	});
```

- `.response(sse(schema))` is optional. Without it, the event type is inferred
  from what the handler yields, and events aren't validated.
- A status is either a stream or a regular body, not both.

## Read Events

The response `body` is an async iterable of events:

```ts
const response = await client.notifications();

if (response.status === 200) {
	for await (const event of response.body) {
		console.log(event.data.message);
	}
}
```

```ts
type SseEvent<T> = {
	/** The yielded value. */
	data: T;
	/** The last event ID: this event's `id`, or the previous one's. */
	id?: string;
	/** The event name. */
	event?: string;
	/** The reconnection time the server suggests, in milliseconds. */
	retry?: number;
};
```

Pass a `signal` to cancel the request and the stream:

```ts
const controller = new AbortController();
const response = await client.notifications(undefined, {
	signal: controller.signal,
});
```

## Event IDs and Names

Yield `sseEvent()` to give an event an `id`, a name or a retry hint:

```ts
import { sseEvent } from "@rest-rpc/server";

const notifications = route.get("/notifications").handler(async function* () {
	yield { postId: "post_1", message: "Ada liked your post" };
	yield sseEvent(
		{ postId: "post_2", message: "Grace liked your post" },
		{ id: "event_2", event: "post.liked", retry: 2_000 },
	);
});
```

`sseEvent()` throws when `id` or `event` contains a line break, or `retry`
isn't a whole number of milliseconds.

## Errors

Throw a defined error before the stream starts to send an error response:

```ts
const notifications = route
	.get("/notifications")
	.response(sse(z.object({ postId: z.string(), message: z.string() })))
	.error("UNAUTHORIZED", { status: 401 })
	.handler(({ context, errors }) => {
		if (!context.user) throw errors.UNAUTHORIZED();
		return streamNotifications(context.user);
	});
```

:::warning
Once the first event is sent, the status can't change. An error thrown
during the stream, or an event that fails validation, ends the stream instead,
and the client's loop throws. [`onError`](/docs/server/interceptors#report-errors)
reports it on the server.
:::

## Stop and Resume

The handler's `signal` aborts when the client disconnects:

```ts
const notifications = route
	.get("/notifications")
	.headers(z.object({ "last-event-id": z.string().optional() }))
	.handler(async function* ({ headers, signal }) {
		let after = headers["last-event-id"];
		while (!signal.aborted) {
			const notification = await nextNotification({ after, signal });
			after = notification.id;
			yield sseEvent(notification, { id: notification.id });
		}
	});
```

The client doesn't reconnect by itself. To resume, call the route again with
the last event ID:

```ts
let lastEventId: string | undefined;
let retryMs = 3_000;

while (!controller.signal.aborted) {
	try {
		const response = await client.notifications(
			{ headers: { "last-event-id": lastEventId } },
			{ signal: controller.signal },
		);
		for await (const event of response.body) {
			lastEventId = event.id;
			retryMs = event.retry ?? retryMs;
			handleNotification(event.data);
		}
	} catch (error) {
		if (controller.signal.aborted) break;
		if (error instanceof RouteError && error.status < 500) throw error;
	}
	await new Promise((resolve) => setTimeout(resolve, retryMs));
}
```

## Stream Options

Proxies and servers may close a connection that's quiet for too long. Pass
`sse` options to the server:

```ts
createApp(router, {
	sse: { keepAlive: 5_000, initialComment: true },
});
```

```ts
type SseOptions = {
	/**
	 * Sends a comment after this many milliseconds without an event. Set it
	 * lower than your server's idle timeout. Off by default.
	 */
	keepAlive?: number;
	/** Sends a comment right after the headers. Off by default. */
	initialComment?: boolean;
	/** How event data is encoded. JSON by default. */
	format?: SseFormat;
};
```

`respond(stream, { sse })` overrides them for one stream.

### Data Format

Event data is JSON by default. To send values JSON can't, such as `Date`, use
another format, and pass the same one to the server and the client:

```ts
import { sseFormat } from "@rest-rpc/server";

const superjsonEvents = sseFormat({
	serialize: (data) => superjson.stringify(data),
	deserialize: (data) => superjson.parse(data),
});

createApp(router, { sse: { format: superjsonEvents } });
createClient(getContract(), { sse: { format: superjsonEvents } });
```

Streams don't use [body codecs](/docs/http-behavior/encoding), so a format is
the only way to change how events are encoded.
