Skip to content

v1.4.0

Choose a tag to compare

@iwater iwater released this 12 Dec 17:24
· 16 commits to main since this release

Add WebSocket plugin with new onWebSocket API

Summary

Implemented a comprehensive WebSocket plugin with new API design (Scheme B) that provides separate WebSocket event handlers with full access to HTTP upgrade request information.

Changes

  1. TypeScript API (index.ts, HttpServer.nitro.ts):

    • Introduced new onWebSocket(path, handler) API on ConfigServer
    • Added ServerWebSocket class with W3C-compatible API (send(), close(), onmessage, etc.)
    • Enhanced event types with full HTTP upgrade information (path, query, headers)
  2. C++ Bridge (HybridHttpServer.cpp):

    • Implemented WebSocket event forwarding from Rust to JavaScript
    • Added WebSocket operation methods for JavaScript API

Key Features

✅ Full W3C WebSocket API compatibility in JavaScript layer
✅ Separate WebSocket handler API with request context access
✅ Full HTTP upgrade information (path, query, headers) available to handlers
✅ Connection management with unique IDs for message routing
✅ Support for both text and binary message types
✅ Comprehensive error handling and cleanup

API Design

server.onWebSocket('/ws', (ws, request) => {
    console.log('Path:', request.path);
    console.log('Query:', request.query);     // e.g., "token=abc&user=123"
    console.log('Headers:', request.headers); // Full HTTP upgrade headers
    
    ws.onmessage = (e) => {
        ws.send('Echo: ' + e.data);
    };
    ws.onclose = () => {
        console.log('Connection closed');
    };
});

The WebSocket plugin enables real-time bidirectional communication while maintaining full access to HTTP upgrade context, making it suitable for authentication and WebSocket routing scenarios.