Effect CommunityEC
Effect Community•2mo ago•
3 replies
Lloyd

Integrating `HttpApi` with WebSockets in Effect Typescript Library

Question about integrating HttpApi with a Web Sockets endpoint. I have a minimal setup where I've squished RPC and HttpApi together using the HttpLayerRouter and have been wanting to expand this to include a route for handling web sockets. As I've gone down the rabbit hole I've not found any good example of an effect-first web socket server and the resulting work around I've found is to simply serve up two ports, one with HttpLayerRouter and another with Bun.serve():
const HttpLive = Effect.gen(function* () {
  const config = yield* ServerConfig;
  yield* Effect.log("Starting server with WebSocket support at /ws");

  // Initialize presence service
  const presence = yield* makePresenceService;

  // Get the runtime for running Effects from WebSocket handlers
  const runtime = yield* Effect.runtime<never>();

  const AllRouters = Layer.mergeAll(ApiRouter, RpcRouter);

  // Create Bun WebSocket server on a separate port
  Bun.serve<WebSocketConnectionData>({
    port: config.port + 1; // WebSocket on port 9001,
    hostname: config.hostname,
    fetch: ()=>{}, // handle scope and upgrade
    websocket: {} // all the ws magic 🪄
  });
  yield* Effect.log(
    `Bun WebSocket server running on ws://${config.hostname}:${wsPort}/ws`,
  );

  return HttpLayerRouter.serve(AllRouters).pipe(
    HttpServer.withLogAddress,
    Layer.provide(DevTools.layer()),
    Layer.provideMerge(BunHttpServer.layerConfig(ServerConfig)),
  );
}).pipe(Layer.unwrapEffect, Layer.launch);


Running the Bun.serve inside the effect feels a bit cursed, but it works 🤷 If anyone has already setup a web socket route using HttpApi could help with how this could be done using effect-platform then I'm all ears
Was this page helpful?