Documentation
sveltekit-sse-utils provides utility functions to implement streaming rpc in sveltekit.
Installation
npm i zod devalue sveltekit-sse-utils
Usage in +server.ts
import { createSSEHandler, serveSSE } from "sveltekit-sse-utils";
import z from "zod";
const handler = createSSEHandler(
async function* ({ event, input, signal }) {
for (let i = 0; i < 10; i++) {
yield `sending updates for ${input.name} ${i}`;
await new Promise((resolve) => setTimeout(resolve, 1000));
}
},
z.object({
name: z.string(),
}),
);
export type UpdatesHandler = typeof handler;
export const GET = (event) => serveSSE({ event, handler });
Usage in +page.svelte
<script lang="ts">
import { sseStream, type ExtractGeneratorValueType } from 'sveltekit-sse-utils';
import type { UpdatesHandler } from './api/updates/+server';
let messages: ExtractGeneratorValueType<UpdatesHandler>[] = [];
async function getUpdates() {
const ac = new AbortController();
const stream = sseStream<UpdatesHandler>('/api/updates', {
input: {
name: 'SvelteKit'
},
signal: ac.signal
});
try {
for await (const data of stream) {
messages.push(data);
messages = messages;
}
} catch (err) {
console.error(err);
}
}
</script>
<button on:click={getUpdates}>Get updates</button>
{#each messages as message}
<p>{message}</p>
{/each}