From 811a49e16bb30a949e2782a9b3df656c5cb4d596 Mon Sep 17 00:00:00 2001 From: bastiaanv Date: Mon, 25 Jul 2022 14:32:09 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9D=20docs:=20Added=20documentations?= =?UTF-8?q?=20about=20Server-Sent-Events?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- documentation/docs/03-routing.md | 70 ++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/documentation/docs/03-routing.md b/documentation/docs/03-routing.md index 18029e9e25ff..aa67bb2098b7 100644 --- a/documentation/docs/03-routing.md +++ b/documentation/docs/03-routing.md @@ -419,3 +419,73 @@ assert.equal( ``` To express a `%` character, use `%25`, otherwise the result will be malformed. + +### Server Sent Events (SSE) + +It is possible to connect your clients to Sveltekit and set it up to send events from the server to your clients. This is also known as [Server-Sent Events (SSE)](https://en.wikipedia.org/wiki/Server-sent_events). This is an alternative to WebSockets, and is supported by all modern browsers. SSE can be implemented as follows, with a chat application as example: + +```js +/// file: src/routes/[id].js +// Store all connections in a set-map +const clients = new Set(); + +export const GET = ({ params }) => { + let controller; + + return { + // These headers are important for the browser to detect a SSE request + headers: { + 'Content-Type': 'text/event-stream', + Connection: 'keep-alive', + 'Cache-Control': 'no-cache' + }, + body: new ReadableStream({ + start: (_) => { + controller = _; + clients.add({ id: params['id'], connection: controller }); + }, + cancel: () => { + clients.delete({ id: params['id'], connection: controller }); + } + }) + }; +}; + +export const POST = async ({ request, params }) => { + const encoder = new TextEncoder(); + const message = await request.text(); + for (const { id, connection } of clients) { + if (id === params['id']) { + continue; + } + + // First format the message correctly with 'data: ' as prefix and 2 new lines as suffix + // Then encode the message to a Uint8Array to be sent to the client + connection.enqueue(encoder.encode('data: ' + message + '\n\n')); + } + + return { status: 204 }; +}; +``` + +```html +/// file: src/routes/index.svelte + + +```