How to host a SvelteKit app with Server Side Events online?

181 views Asked by At

I recently completed an app that simulates Robert's Rules by having each user's client emit event. I did this through the javascript EventSource which works perfectly when hosted locally. However, when trying to host it on the web, I ran into a million issues.

Here is a snapshot of the code:

onMount(() => {
        const source = new EventSource(`/rooms/${roomId}/activity`, {
            withCredentials: false
        });
        const event = SSEvents[roomId as keyof typeof SSEvents];
        source.addEventListener(event, (e) => {
            const message = JSON.parse(e.data);
            const membername: string = message.name;
            delete message.name;
            if (message.type === 'set') {
                messageStore.update(($messageStore) => $messageStore.set(membername, message));
                if (membername === $user?.toString()) {
                    selectedValue = message.status;
                }
            }
            if (message.type === 'delete') {
                messageStore.update(($messageStore) => {
                    $messageStore.delete(membername);
                    return $messageStore;
                });
            }
        });
        return () => {
            source.close();
        };
    });
  1. On Vercel, the EventSource would cause a 504 "Timeout" error as--I assume--the event stream would time out before a change was made.
  2. On Cloudflare, the EventSource would keep appearing on the network tab of the debug menu but it would display as blank.
  3. On Netlify, the EventSource would report a 502 "Bad Gateway" error.

How can I host a SSE app on the web?

1

There are 1 answers

2
Ennoriel On BEST ANSWER

It is not possible to use sse on vercel, netlify or cloudflare because these providers are serverless. The server will not remain on and any request will timeout after 10 secs. They might have implemented protection when the response has the stream content type

You will have to build your application with the node adapter and host it on a non serverless provider.