Skip to main content
Modelence provides built-in WebSocket support for real-time, bidirectional communication between your server and clients. Built on Socket.IO with MongoDB adapter for horizontal scaling, WebSockets enable live updates, notifications, collaborative features, and more.

Overview

Modelence WebSocket implementation includes:
  • Real-Time Communication - Instant bidirectional messaging between server and clients
  • Channel-Based Architecture - Organize connections into logical channels with access control
  • Authentication Integration - Automatic user authentication for WebSocket connections
  • Horizontal Scaling - MongoDB adapter enables scaling across multiple server instances
  • Type Safety - Full TypeScript support with generic types for message payloads
  • Built on Socket.IO - Leverages the robust Socket.IO library with fallback support

How WebSockets Work

Connection Flow

  1. Client Connection - Client initiates WebSocket connection to the server
  2. Authentication - Connection is automatically authenticated using the session token
  3. Channel Registration - Channels are registered in your Module
  4. Join Channels - Client joins specific channels by category and ID
  5. Real-Time Messages - Server broadcasts messages to all clients in a channel
  6. Automatic Reconnection - Socket.IO handles reconnection on network interruptions

Channel Architecture

Channels are organized using a category:id pattern:
  • Category - Defines the type of channel (e.g., “chat”, “notifications”, “game”)
  • ID - Unique identifier for the specific channel instance (e.g., room ID, user ID)
  • Access Control - Optional server-side function to control who can join
Example channel names:
  • chat:room123 - Chat room with ID “room123”
  • notifications:user456 - Notifications for user “user456”
  • game:match789 - Game updates for match “match789”

Server-Side Setup

Creating Server Channels

Create a server channel file to define your channel:

Registering Channels in Module

Channels are registered in your Module definition:

Broadcasting Messages

Use the channel to broadcast messages to all connected clients:

Channel with Access Control

Add access control to restrict who can join a channel:

Client-Side Setup

Creating Client Channels

Define a client channel to receive messages:

Initialize WebSockets

Start WebSocket connection and register channels in your app entry point:

Joining and Leaving Channels

Join specific channels to start receiving messages:

Complete Example

Here’s a complete example of a real-time chat system:

Server

Channel Definition:
Module Registration:
App Startup:

Client

Channel Definition:
App Initialization:
Using in Components:

Horizontal Scaling

Modelence WebSockets use the Socket.IO MongoDB adapter, which enables horizontal scaling across multiple server instances:

How It Works

  1. Shared MongoDB Collection - All server instances share a MongoDB collection (_modelenceSocketio)
  2. Message Distribution - When one server broadcasts a message, it’s stored in MongoDB
  3. Cross-Instance Delivery - All server instances receive the message and deliver to their connected clients
  4. Automatic Cleanup - Messages expire after 1 hour (TTL index on createdAt field)

Configuration

The MongoDB adapter is automatically configured when you:
  1. Initialize Modelence with MongoDB connection
  2. Register channels in your Module
  3. Start your application
No additional configuration needed! The scaling happens automatically.

Load Balancing

When deploying multiple instances:
Nginx example:

Security Best Practices

Authentication

  • Automatic Auth - WebSocket connections are automatically authenticated using session tokens
  • Access Control - Use the second parameter in ServerChannel to restrict channel access
  • Token Validation - Session tokens are validated on every connection

Channel Security

Data Validation

Always validate data before broadcasting:

Performance Considerations

Channel Granularity

  • Fine-grained - Create specific channels for individual resources (e.g., chat:room123)
  • User-specific - Use user IDs for personal channels (e.g., notifications:user456)
  • Avoid Global - Don’t broadcast to all users; use targeted channels

Message Size

Keep message payloads small for optimal performance:

TypeScript Support

Full TypeScript support with generic types:

API Reference

Server Types

  • WebsocketServerProvider - Interface for WebSocket server providers (API Reference)
  • ServerChannel - Server-side channel class (API Reference)

Client Types

  • WebsocketClientProvider - Interface for WebSocket client providers (API Reference)
  • ClientChannel - Client-side channel class (API Reference)

Functions

Common Use Cases

Real-Time Chat

Live Notifications

Collaborative Editing

Live Dashboard

Gaming

Troubleshooting

Connection Issues

Problem: Client can’t connect to WebSocket server Solutions:
  • Verify server is started with channels registered in Module
  • Check that MongoDB is connected
  • Ensure firewall allows WebSocket connections
  • Verify CORS settings if connecting from different origin

Messages Not Received

Problem: Client joined channel but not receiving messages Solutions:
  • Verify channel category matches exactly between client and server
  • Check access control function if channel is protected
  • Ensure user is authenticated if channel requires auth
  • Confirm channels are registered in startWebsockets()

Scaling Issues

Problem: Messages not reaching all clients across multiple servers Solutions:
  • Verify MongoDB connection is shared across all instances
  • Check that _modelenceSocketio collection exists
  • Ensure TTL index was created successfully
  • Review MongoDB logs for adapter errors

Next Steps

  • Explore the Authentication docs for securing WebSocket connections
  • Check out the Tutorial for complete application examples
  • Review Stores documentation for persisting real-time data
  • Learn about Modules for organizing your application