Remixjs, SSE

Hey everyone

The problem

I can’t keep the server sent event connection alive for more than ~1 minute

I get this error in the browser console

GET https://domain.com/api/sse 502

This is my resource route loader code

import { eventStream } from "remix-utils";
import { emitter } from "~/utils/notification/emitter.server";
import { Events, EventsType } from "~/utils/notification/events";
import { requireUser } from "~/utils/sessions/user.server";
import type { Notification } from "@prisma/client";

export async function loader({ request }: LoaderArgs) {
  const user = await requireUser(request);

  return eventStream(request.signal, function setup(send) {
    function handle(notification: Notification) {
      if (notification.userId !== user.id) return;

      send({ event: Events.newNotification, data: notification.id });
    }

    emitter.on(EventsType.notification, handle);

    return function clear() {
      emitter.off(EventsType.notification, handle);
    };
  });
}

the event works fine for about a minute then not

Hey @debiip what you’re experiencing may be explained here in our docs. Our Fly Proxy ends idle connections after 1 minute. So you’ll need some reconnection logic.

thanks for reply

is there an example on how to do that

I’m not an expert on this topic, but our docs say that the ioredis Redis client handle those you can check out their code. It’s about your client detecting when the connection is closed and then reconnecting.

You could also have your server send regular “hearbeat” events to prevent the connection from being idle. But be sure to cleanup these properly when the clients leave your site or you’ll have memory leaks.

1 Like

thanks

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.