• Stars
    star
    267
  • Rank 153,621 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 1 year ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Server Sent Events with SvelteKit

SvelteKit SSE

This library provides an easy way to produce and consume server sent events.

Install with:

npm i -D sveltekit-sse

Warning

previously npm i -D sveltekit-server-sent-events

Create your server sent event with:

// src/routes/custom-event/+server.js
import { event } from 'sveltekit-sse'

/**
 * @param {number} milliseconds
 * @returns
 */
function delay(milliseconds){
  return new Promise(function run(){
    setTimeout(r, milliseconds)
  })
}

export function GET() {
  return event(async function run(emit){
    while (true) {
      emit(`${Date.now()}`)
      await delay(1000)
    }
  }).toResponse()
}

and consume it on your client with:

<script>
  // src/routes/+page.svelte
  import { source } from 'sveltekit-sse'
  const value = source('/custom-event')
</script>
{$value}

Multiple events

All major browsers will limit the number of parallel http connections.

One solution to this problem is using http2.

However, for various reasons not everyone can serve http2 responses, in that case you can use the same http1 connection to emit multiple events.

// src/routes/events/+server.js
import { events } from 'sveltekit-sse'

/**
 * @param {number} milliseconds
 * @returns
 */
function delay(milliseconds){
  return new Promise(function run(){
    setTimeout(r, milliseconds)
  })
}

export function GET() {
  return events(async function run(emit){
    while (true) {
      emit('event-1', `/events (1) says: ${Date.now()}`)
      emit('event-2', `/events (2) says: ${Date.now()}`)
      emit('event-3', `/events (3) says: ${Date.now()}`)
      await delay(2000)
    }
  }).toResponse()
}

and consume it on your client with:

<script>
  import { source } from 'sveltekit-sse'

  const connection = source('/events')
  const value1 = connection.select('event-1')
  const value2 = connection.select('event-2')
  const value3 = connection.select('event-3')
</script>

{$value1}
<br />
{$value2}
<br />
{$value3}

Transform

While on the client, you can transform the stream into any type of object you want by using source::select::transform.

The transform method receives a ReadableStream, which you can use to read incoming messages from the source.

Here's an example how to use it.

<script>
  import { source } from 'sveltekit-sse'

  const connection = source('/custom-event')
  const channel = connection.select('message')

  const transformed = channel.transform(function start(stream) {
    let state = {
      /** @type {Array<function(string):void>}*/
      listeners: [],
    }
    const reader = stream.getReader()
    const store = {
      subscribe(callback) {
        if (!state.listeners.includes(callback)) {
          state.listeners.push(callback)
        }

        return function stop(){
          state.listeners = state.listeners.filter(function pass(value){
            return value !== callback
          })
        }
      },
    }

    const listen = async function () {
      let value = ''
      while (({ value } = await reader.read())) {
        state.listeners.forEach(function run(callback){
          callback(value)
        })
      }
    }

    listen()

    return store
  })

  $: console.log({$transformed})
</script>

Custom Headers

The standard EventSource class does not permit setting custom headers or manipulating the underlying request options.

This library achieves client side event sourcing using fetch.

Note

Custom headers are only available since version 0.4.0.

The following will set a Authorization: Bearer ... header to the underlying http request.

<script>
  import { source } from 'sveltekit-sse'

  const data = source("/event", {
    headers: {
      "Authorization": "Bearer ..."
    }
  })
</script>
{$data}

Reconnect

You can reconnect to the stream whenever the stream closes by invoking Event::connect.

<script>
  import { source } from 'sveltekit-sse'

  const data = source('/custom-event').onClose(function stop({ connect }) {
    connect()
    console.log('reconnecting')
  })

  setTimeout(function run() {
    data.close()
  }, 5000)

</script>
{$data}

More Repositories

1

svelte-liquid-swipe

Svelte
64
star
2

svelte-animated-pixels

JavaScript
18
star
3

catpaw

An opinionated dependency injection library for amphp.
PHP
15
star
4

java-springboot-svelte3-ssr-template

A Java Spring Boot template that renders Svelte components server side.
JavaScript
15
star
5

svelte-3-jssr-starter

Java
12
star
6

svelte-f7-starter

SCSS
10
star
7

svelte-framework7-template

Svelte using framework7 template (includes Capacitor)
CSS
7
star
8

sveltekit-server-session

Server sessions made easy with SvelteKit
JavaScript
7
star
9

svelte-starter

A Svelte template using Vite and TypeScript
JavaScript
5
star
10

bunfire

using Zig + Bun + Svelte to render svelte files on the server and hydrate them over a file system router
JavaScript
4
star
11

java-svelte3-ssr

Java SSR for Svelte (requires GraalVM)
JavaScript
4
star
12

svelte-flare

JavaScript
4
star
13

svelte-slotify

A small piece of code that allows you to manage svelte components as named slots (kinda)
JavaScript
3
star
14

svelte-anchorable

Create svelte stores and sync them with location.hash
JavaScript
2
star
15

java-quarkus-svelte-template

A quarkus project template using svelte with typescript
Java
2
star
16

observable-websocket-state

HTML
2
star
17

json-to-php

Convert Json data to Php classes.
PHP
2
star
18

sveltekit-sse-issue-10

JavaScript
1
star
19

catpaw-queue

An execution queue for catpaw using tagging and FIFO ordering within each tagged queue.
PHP
1
star
20

catpaw-starter

Starter template for catpaw-core
PHP
1
star
21

svelte-custom-code-highlight

A standard web component that can be used as a plain html tag.
Svelte
1
star
22

php-simple-shared-memory

PHP
1
star
23

catpaw-web

A web server for catpaw-core
PHP
1
star
24

catpaw-unsafe

Manage errors in php.
PHP
1
star
25

sveltekit-server-session-example

An example of how to use sveltekit-server-session.
JavaScript
1
star