Protocols

WebSockets

The native engine serves WebSockets on the same port as HTTP, with nothing to install. Socket.IO and ws adapters plug in when you need those libraries, and WebSockets can be turned off entirely.

Overview

MoroJS serves WebSockets from its native engine by default: RFC 6455 on the same port as HTTP, with no extra dependency. When you need the Socket.IO protocol or the ws library, an adapter swaps the backend and app.websocket() stays the same.

Without MoroJS

  • A WebSocket library to install and wire to the server
  • Different APIs for different libraries
  • Hard to switch between solutions
  • A second port or a separate upgrade handler

With MoroJS

  • Built into the native engine, on the HTTP port
  • Same API on the engine and on every adapter
  • Socket.IO and ws adapters when you need them
  • Nothing to install or configure by default
Universal WebSocket Usage
1// Same API on the native engine and on every adapter
2app.websocket('/chat', {
3  'join-room': (socket, data) => {
4    socket.join(data.room);
5    socket.to(data.room).emit('user-joined', {
6      username: data.username,
7      room: data.room,
8      timestamp: new Date()
9    });
10    return { success: true, room: data.room };
11  },
12
13  'send-message': (socket, data) => {
14    socket.to(data.room).emit('new-message', {
15      id: Date.now(),
16      message: data.message,
17      sender: data.username,
18      room: data.room,
19      timestamp: new Date()
20    });
21    return { success: true };
22  },
23
24  'disconnect': (socket) => {
25    // Cleanup logic
26    console.log(`User ${socket.id} disconnected`);
27  }
28});

Built in

The native engine serves WebSockets itself, on the same port as HTTP.

Pluggable

Socket.IO and ws adapters for those libraries' protocols and features.

Consistent

Same API on the engine and on every adapter. Switch between them easily.

Raw Frames for Plain WebSocket Peers
1// Browsers calling WebSocket.send('hello'), load testers and non-Moro
2// services speak raw frames, not { event, data } envelopes. Register the
3// namespace with { raw: true }: text frames reach 'message' as strings,
4// binary frames reach 'binary' as Buffers, replies go through socket.send().
5app.websocket('/ws', {
6  connection: (socket) => console.log('open', socket.id),
7  message: (socket, text) => socket.send(text),        // text in, text out
8  binary: (socket, bytes) => socket.send(bytes, true), // binary in, binary out
9  disconnect: (socket) => console.log('closed', socket.id),
10}, { raw: true });
11
12// A string or Buffer returned from a handler is the reply frame
13app.websocket('/shout', {
14  message: (socket, text) => text.toUpperCase(),
15}, { raw: true });
16
17// Supported by the native engine and the ws adapter
18// (Socket.IO speaks its own protocol and ignores raw). On the ws adapter
19// namespaces live below its base path: ws://host/ws/shout

How It Works

With no adapter configured, the native engine answers the upgrade and serves the connection itself; a valid handshake never enters JavaScript (@morojs/engine 1.1.15 or later), and socket.ip and socket.headers are read from the connection the first time a handler asks for them.

The Socket.IO and ws adapters attach to a Node.js http.Server, so MoroJS selects the Node.js server when one of them is configured. On the Node.js server with no adapter configured (engine: 'node', or where the engine cannot load), an installed socket.io or ws is detected and used, in that order. websocket: false turns WebSockets off for HTTP-only apps.

WebSocket Adapter Configuration

Choose Your WebSocket Backend
1import { createApp, SocketIOAdapter, WSAdapter } from '@morojs/moro';
2
3// Option 1: The native engine (default, nothing to configure)
4const app = await createApp(); // WebSockets on the HTTP port
5
6// Option 2: Explicit Socket.IO adapter
7const app = await createApp({
8  websocket: {
9    adapter: new SocketIOAdapter(),
10    options: {
11      cors: { origin: '*' },
12      path: '/socket.io/',
13      pingTimeout: 60000
14    }
15  }
16});
17
18// Option 3: Native WebSocket adapter (lightweight)
19const app = await createApp({
20  websocket: {
21    adapter: new WSAdapter(),
22    options: {
23      path: '/ws',
24      maxPayloadLength: 100 * 1024 * 1024 // 100MB
25    }
26  }
27});
28
29// Option 4: Disable WebSockets (HTTP-only)
30const app = await createApp({ websocket: false });

Advanced WebSocket Features

WebSocket Event Handling
1// Based on actual feature-showcase implementation
2app.websocket('/chat', {
3  join: (socket, data) => {
4    socket.join('chat-room');
5    socket.to('chat-room').emit('user-joined', {
6      message: `${data.username} joined the chat`
7    });
8    return { success: true, message: 'Joined chat room' };
9  },
10
11  message: (socket, data) => {
12    socket.to('chat-room').emit('message', {
13      username: data.username,
14      message: data.message,
15      timestamp: new Date().toISOString()
16    });
17    return { success: true };
18  }
19});
20
21// Simple WebSocket endpoint without rooms
22app.websocket('/notifications', {
23  connection: (socket) => {
24    console.log('Notification client connected');
25    socket.emit('welcome', {
26      message: 'Connected to notifications'
27    });
28  },
29
30  disconnect: (socket) => {
31    console.log('Notification client disconnected');
32  },
33
34  subscribe: (socket, data) => {
35    const { channel } = data;
36    socket.join(channel);
37    return { success: true, channel };
38  }
39});
Authenticating a Connection
1// The connection hook runs once per socket at open and sees the
2// handshake. verifyToken() is your own function.
3app.websocket('/secure-chat', {
4  connection: (socket) => {
5    const user = verifyToken(socket.headers?.authorization);
6    if (!user) {
7      socket.emit('error', { message: 'Authentication required' });
8      socket.disconnect();
9      return;
10    }
11
12    socket.data.user = user;        // per-connection storage
13    socket.join(`user:${user.id}`); // a room per user
14    socket.emit('authenticated', { user });
15  },
16
17  'private-message': (socket, data) => {
18    const user = socket.data.user;
19    if (!user) return { success: false, error: 'Not authenticated' };
20
21    socket.to(`user:${data.targetUserId}`).emit('private-message', {
22      from: user.name,
23      message: data.text
24    });
25    return { success: true };
26  }
27});

WebSocket Adapter Comparison

AdapterBundle SizePerformanceFeaturesUse Case
Native engine (default)None (ships with MoroJS)Fastest of the threeHTTP port, backpressure, permessage-deflate, raw framesProduction, real-time, high traffic
Socket.IO~244KBGoodRich (rooms, namespaces)Feature-rich apps
ws~8KBVery goodStandards-compliant, lightweightApps already built on ws
None0KBN/AHTTP onlyREST APIs

Installation Guide

Native Engine

No additional deps
# The default

Socket.IO Projects

npm install socket.io
# SocketIOAdapter

ws Library

npm install ws @types/ws
# WSAdapter

HTTP-Only

No additional deps
# Just disable WS

Coming from uWebSockets.js

The uWebSockets.js adapter was removed in MoroJS 1.8.24; the native engine replaced it. websocket.adapter: 'uws' is still accepted and now means the engine's own WebSocket support, so an existing configuration keeps working. The UWebSocketsAdapter export is gone; remove imports of it. The full steps are in the HTTP Engine guide.

Next Steps