Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extended API to support WebSocket #24

Merged
merged 18 commits into from
Dec 8, 2024
Merged

Extended API to support WebSocket #24

merged 18 commits into from
Dec 8, 2024

Conversation

rphlmr
Copy link
Owner

@rphlmr rphlmr commented Nov 30, 2024

Add WebSocket support for node adapter and the dev server

Additional changes:

  • honoOptions is deprecated in favor of app?: Hono<E>;
    It offers the same option but makes this library more composable
  • New option for Node: onServe. It's a callback invoked after the server has started.

Example:

import type { WSContext } from "hono/ws";
import { createHonoServer } from "react-router-hono-server/node";

console.log("loading server");

// Store connected clients
const clients = new Set<WSContext>();

export default await createHonoServer({
  useWebSocket: true,
  // 👆 Unlock this 👇 from @hono/node-ws
  configure: (app, { upgradeWebSocket }) => {
    app.get(
      "/ws",
      upgradeWebSocket((c) => ({
        // https://hono.dev/helpers/websocket
        onOpen(_, ws) {
          console.log("New connection ⬆️");
          clients.add(ws);
        },
        onMessage(event, ws) {
          console.log("Context", c.req.header("Cookie"));
          console.log("Event", event);
          console.log(`Message from client: ${event.data}`);
          // Broadcast to all clients except sender
          clients.forEach((client) => {
            if (client.readyState === 1) {
              client.send(`${event.data}`);
            }
          });
        },
        onClose(_, ws) {
          console.log("Connection closed");
          clients.delete(ws);
        },
      }))
    );
  },
});

@rphlmr
Copy link
Owner Author

rphlmr commented Nov 30, 2024

fix #23

Copy link

pkg-pr-new bot commented Nov 30, 2024

Open in Stackblitz

npm i https://pkg.pr.new/rphlmr/react-router-hono-server@24

commit: 1d742a9

@rphlmr rphlmr changed the title Feat/extended Extended API to support WebSocket Dec 2, 2024
@rphlmr rphlmr merged commit aeebbb7 into main Dec 8, 2024
5 checks passed
@rphlmr rphlmr deleted the feat/extended branch December 8, 2024 15:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant