Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@dardanbujupaj
Copy link
Contributor

@dardanbujupaj dardanbujupaj commented Nov 16, 2025

This PR adds an alternative parameter type for defineWebsocketHandler, so that we can access event when defining crossws hooks.
This allows us to use methods like getRouterParam(event, name) similar to http handlers.
It also resolves #715.

I saw that there's also #1149 open, which might relate to this. But I think this should just work together.

Example

Use router param to subscribe/publish to a topic.

import { defineWebSocketHandler, H3, serve, getRouterParam } from "h3-patched";
import { plugin as ws } from "crossws/server";

const app = new H3();

app.get(
  "/ws/:room",
  defineWebSocketHandler((event) => {
    const room = getRouterParam(event, "room") as string;

    return {
      open(peer) {
        console.log(`Peer ${peer.id} connected to room ${room}`);
        peer.subscribe(room)
      },
      message(peer, message) {
        console.log(`Received message from ${peer.id} for room ${room}: ${message.data}`);
        peer.publish(room, message.data);
      },
    };
  }),
);

serve(app, {
  plugins: [ws({ resolve: async (req) => (await app.fetch(req)).crossws })],
});

Summary by CodeRabbit

  • New Features

    • defineWebSocketHandler now accepts hooks as either static configuration or as a dynamic function that resolves hooks per request.
  • Documentation

    • Updated API documentation to reflect enhanced parameter flexibility.
  • Tests

    • Added test coverage for function-based hooks configuration.

✏️ Tip: You can customize this high-level summary in your review settings.

@dardanbujupaj
Copy link
Contributor Author

There's also defineWebSocket, but I wasn't sure about the use case for that, so I left it for now.
Glad for inputs about that 🙃

@coderabbitai
Copy link

coderabbitai bot commented Dec 8, 2025

📝 Walkthrough

Walkthrough

The defineWebSocketHandler function signature was extended to accept hooks either as a direct object or as a function that receives an H3Event and returns hooks. This enables dynamic hook resolution at request time. Documentation and tests were updated to reflect the new capability.

Changes

Cohort / File(s) Summary
Documentation Update
docs/2.utils/9.more.md
Updated WebSocket handler usage examples to reflect the new parameterless API signature, removing the deprecated defineWebSocketHandler(hooks) pattern.
Handler Implementation
src/utils/ws.ts
Extended defineWebSocketHandler signature to accept hooks as either Partial<WebSocketHooks> or a function (event: H3Event) => Partial<WebSocketHooks> | Promise<Partial<WebSocketHooks>>. Added H3Event import and dynamic hook resolution logic that calls the function when provided, binding resolved hooks to the crossws property.
Test Coverage
test/ws.test.ts
Added test case validating that defineWebSocketHandler correctly accepts a function returning hooks and properly attaches them to the response with 426 status and crossws property.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • API signature change: Verify backward compatibility and that both direct hooks and function-returning hooks work correctly.
  • Event handling: Ensure H3Event is properly passed and hooks are resolved at the right lifecycle point.
  • Async resolution: Confirm proper handling of Promise-based hook resolution.
  • Test validation: Check that the new test case covers both success and edge cases adequately.

Poem

🐰 A handler now sees the request's intent,
No longer blind when down the route you went,
The WebSocket hops with H3Event in paw,
Router params dance—no more API law!
The crossws knows thy secret ID well,
A feature for which the bunnies do tell. 🌙✨

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed The PR implements the core requirement from issue #715 by allowing access to the H3Event within websocket handlers via a callback parameter, enabling use of getRouterParam and other event-based utilities.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the linked issue: documentation updates reflect the new API, implementation adds event-callback support to defineWebSocketHandler, and tests verify the new functionality.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Title check ✅ Passed The PR title accurately summarizes the main change: adding support for a callback function that receives an event parameter to defineWebSocketHandler.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Member

@pi0 pi0 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks ❤️

@pi0 pi0 changed the title feat: allow event callback as parameter to defineWebSocketHandler feat(efineWebSocketHandler): support callback with event Dec 8, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/utils/ws.ts (1)

24-28: Add @param JSDoc tag for documentation generation.

The JSDoc comment lacks a @param tag, which likely causes the auto-generated documentation to show an empty signature defineWebSocketHandler(). Adding parameter documentation will improve both the generated docs and IDE intellisense.

 /**
  * Define WebSocket event handler.
  *
+ * @param hooks - WebSocket hooks object or a function that receives an H3Event and returns hooks
  * @see https://h3.dev/guide/websocket
  */
test/ws.test.ts (1)

23-30: Test looks good; consider adding async function test.

The test correctly verifies the synchronous function argument case. Since the type signature supports Promise<Partial<WebSocketHooks>>, consider adding a test for the async case to ensure the Promise is correctly passed through.

   it("should attach the provided hooks with function argument", () => {
     const wsHandler = defineWebSocketHandler(() => hooks);
     const res = wsHandler({} as any);
     expect(res).toBeInstanceOf(Response);
     expect((res as Response).status).toBe(426);
     // expect((res as Response).statusText).toBe("Upgrade Required");
     expect((res as any).crossws).toEqual(hooks);
   });
+
+  it("should attach the provided hooks with async function argument", async () => {
+    const wsHandler = defineWebSocketHandler(async () => hooks);
+    const res = wsHandler({} as any);
+    expect(res).toBeInstanceOf(Response);
+    expect((res as Response).status).toBe(426);
+    // crossws should be a Promise that resolves to hooks
+    await expect((res as any).crossws).resolves.toEqual(hooks);
+  });
 });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8319767 and f864742.

📒 Files selected for processing (3)
  • docs/2.utils/9.more.md (1 hunks)
  • src/utils/ws.ts (2 hunks)
  • test/ws.test.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/utils/ws.ts (4)
src/index.ts (4)
  • WebSocketHooks (230-230)
  • H3Event (24-24)
  • EventHandler (35-35)
  • defineHandler (52-52)
src/event.ts (1)
  • H3Event (33-144)
src/types/handler.ts (1)
  • EventHandler (12-18)
src/handler.ts (1)
  • defineHandler (36-60)
🔇 Additional comments (1)
src/utils/ws.ts (1)

29-47: Implementation is correct; async hooks are properly supported by h3 and crossws.

The logic correctly distinguishes between direct hooks and function-based hooks. The type signature supports returning Promise<Partial<WebSocketHooks>>, and h3's event handler system explicitly awaits Promise results returned from handlers. Similarly, crossws's upgrade and lifecycle hooks support async execution, so passing a Promise to the crossws property is the intended pattern for lazy or async hook resolution.

Define WebSocket hooks.

### `defineWebSocketHandler(hooks)`
### `defineWebSocketHandler()`
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Documentation signature appears incomplete.

The auto-generated signature shows defineWebSocketHandler() with no parameters, but the implementation accepts a required hooks parameter. This may be an issue with the JSDoc comment in src/utils/ws.ts not documenting the parameter, causing automd to generate an incomplete signature.

Consider adding a @param JSDoc tag to the function in src/utils/ws.ts to ensure the documentation reflects the actual API.

🤖 Prompt for AI Agents
In docs/2.utils/9.more.md around line 84, the generated signature for
defineWebSocketHandler() is missing its required parameter because the
implementation in src/utils/ws.ts does not document the parameter; update
src/utils/ws.ts by adding a JSDoc @param tag for the required hooks argument
(describe its expected type/shape and whether properties are optional), include
a short description and an example if helpful, and ensure the function JSDoc
block is directly above the function so the docs generator picks it up.

@pi0 pi0 changed the title feat(efineWebSocketHandler): support callback with event feat(defineWebSocketHandler): support callback with event Dec 8, 2025
@pi0 pi0 merged commit 45d1989 into h3js:main Dec 8, 2025
4 checks passed
@they-cloned-me
Copy link

Thank you, @dardanbujupaj @pi0 😍
I had a question about something like this (although in Nitro) two years ago:
nitrojs/nitro#2605

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.

Router params inside websocket handler

3 participants