kit-sse

Type-safe Server-Sent Events for SvelteKit with schema validation

🔒 Type-Safe

Full TypeScript inference from your schema

⚡ Reactive

Built with Svelte 5 runes for seamless reactivity

✅ Validated

Runtime validation via Standard Schema spec

🏷️ Named Events

Support for SSE event types beyond 'message'

📜 History

Access previous messages, not just the latest

🔄 Custom Retry

Configure reconnection with exponential backoff

🚀 Usage

Works with any Standard Schema compatible library (Valibot, Zod, ArkType, etc.)

🔴 Live Demo Connecting

Named events with message history:

Event: History: 0 messages

Waiting for events...

📖 How It Works

kit-sse connects your SvelteKit server to the browser using Server-Sent Events, a simple HTTP-based protocol for real-time updates. On the server, you create a handler that pushes data whenever you have something new. On the client, you call eventSource() with a URL and a schema — it returns a reactive object that updates automatically as messages arrive. The schema validates each message at runtime, so your types are guaranteed to match reality. Everything is reactive: just read .data in your template and Svelte handles the rest.

🔄 Auto-reconnect

Network errors (server restarts, connection drops) automatically trigger reconnection via the native EventSource API. The .state changes to "connecting" while retrying, and any previous .error is cleared once the connection reopens. Your UI can show a "reconnecting" indicator without any extra logic.

🚫 Validation errors are fatal

If the server sends malformed JSON or data that fails schema validation, the connection closes permanently with .state = "error". These are application bugs that won't fix themselves on retry. The .error property contains a descriptive message to help you debug — check your server is sending the correct shape.

🖥️ SSR-safe

During server-side rendering, eventSource() returns a stub with .state = "connecting" and .data = undefined. The real connection only opens in the browser. This prevents hydration mismatches and means you can safely call it at the top level of your component.

🔌 Check isConnected on the server

In long-running server handlers, always check ctx.isConnected before each ctx.push(). Clients can disconnect at any time (navigation, tab close, network loss). Skipping this check wastes server resources and may cause errors when writing to a closed stream.

📝 Standard Schema

The schema you pass is used for runtime validation on incoming messages, not just TypeScript types. This catches malformed data before it reaches your app. Any library implementing the Standard Schema spec works: valibot, zod, arktype, and others.