Skip to main content

Introduction

๐ŸŽฏ What does this module do?โ€‹

The WS (WebSocket) module lets you receive real-time notifications - content updates, order changes, user actions - establishing persistent connections to get instant updates without polling, enabling live features like notifications, live chat, and real-time dashboards.

Think of it as your real-time notification system - instead of repeatedly asking "is there something new?" (polling), WebSocket keeps a connection open and the server pushes updates to you instantly when events occur.


๐Ÿ“– Simple Explanationโ€‹

Every modern application needs real-time updates:

  • ๐Ÿ”” Live Notifications - Instant alerts when something happens
  • ๐Ÿ’ฌ Live Chat - Real-time messaging between users
  • ๐Ÿ“Š Live Dashboards - Auto-updating statistics and metrics
  • ๐Ÿ›’ Order Updates - Instant order status changes
  • ๐Ÿ“ Content Updates - Live content changes and publishing
  • ๐Ÿ‘ฅ User Activity - Real-time user presence and actions
  • ๐Ÿ”„ Data Sync - Automatic synchronization across devices

The problem with polling (repeated requests):

// โŒ Bad - Polling every 5 seconds
setInterval(async () => {
const orders = await Orders.getOrders();
// Check if anything changed
// Wastes bandwidth, delays updates, server load
}, 5000);

Issues:

  • ๐Ÿ”‹ Battery drain - Constant requests waste power
  • ๐Ÿ“ก Network waste - Most requests return "no changes"
  • โฑ๏ธ Delayed updates - Up to 5 seconds delay
  • ๐Ÿ–ฅ๏ธ Server load - Unnecessary requests every few seconds

The WebSocket solution:

// โœ… Good - Real-time WebSocket connection
const { WS } = defineOneEntry('https://your-site.oneentry.cloud', {
token: 'your-app-token'
});

// Subscribe to events
WS.subscribe('order.created', (order) => {
console.log('New order received!', order);
// Instant notification, no polling!
});

WS.subscribe('content.updated', (content) => {
console.log('Content updated!', content);
// Update UI immediately
});

Benefits:

  • ๐Ÿ”‹ Efficient - Single persistent connection
  • ๐Ÿ“ก Real-time - Instant updates, no delay
  • โฑ๏ธ Low latency - Sub-second notification delivery
  • ๐Ÿ–ฅ๏ธ Reduced load - Server pushes only when needed

โœจ Key Conceptsโ€‹

What is WebSocket?โ€‹

WebSocket is a persistent two-way connection between client and server:

  • Persistent Connection - Stays open, no repeated handshakes
  • Bidirectional - Both client and server can send messages
  • Real-Time - Instant message delivery
  • Event-Based - Subscribe to specific events
  • Efficient - Low overhead compared to HTTP polling

WebSocket vs HTTP Pollingโ€‹

FeatureWebSocketHTTP Polling
ConnectionPersistent (stays open)Repeated connections
LatencySub-secondDepends on interval (2-30s)
EfficiencyVery efficientWasteful (many empty responses)
Server LoadLow (events only)High (constant requests)
Battery UsageLowHigh (mobile devices)
Use CaseReal-time updatesAcceptable for non-critical updates

WebSocket Connection Lifecycleโ€‹

1. Client connects to WebSocket server
(WS.connect())
โ†“
2. Connection established
(onOpen event fires)
โ†“
3. Client subscribes to events
(WS.subscribe('event.name', callback))
โ†“
4. Server sends events when they occur
(Instant delivery)
โ†“
5. Client receives event messages
(Callback function executes)
โ†“
6. Connection stays open
(No reconnection needed)
โ†“
7. Client disconnects when done
(WS.disconnect())

Common WebSocket Eventsโ€‹

Event TypeDescriptionExample Use Case
order.createdNew order placedShow "New Order!" notification
order.updatedOrder status changedUpdate order status in UI
content.publishedNew content publishedRefresh content list
content.updatedContent editedUpdate displayed content
user.registeredNew user signed upShow new user in admin dashboard
payment.completedPayment processedUpdate order status to "Paid"
product.outOfStockProduct out of stockShow "Out of Stock" badge

Why Use WebSocket Module?โ€‹

BenefitDescription
Real-Time UpdatesInstant notifications, no polling delay
EfficientSingle connection, low overhead
Battery FriendlyNo constant polling on mobile
ScalableServer pushes only when needed
Event-DrivenSubscribe to specific events
Live FeaturesEnable chat, notifications, dashboards

๐Ÿš€ Quick Exampleโ€‹


๐Ÿ“‹ What You Need to Knowโ€‹

1. WebSocket Connection Managementโ€‹

WebSocket connections need to be managed carefully:

Best practices:

  • Check connection state before subscribing
  • Implement reconnection logic
  • Handle connection errors gracefully
  • Disconnect when user logs out

2. Event Subscription Managementโ€‹

Subscribe to events only after connection is established

Best practices:

  • Use named callback functions for easier unsubscription
  • Subscribe after connection is open
  • Unsubscribe when component unmounts
  • Don't subscribe to same event multiple times

3. Event Unsubscriptionโ€‹

Always unsubscribe when done to prevent memory leaks:

Best practices:

  • Unsubscribe in cleanup functions
  • Disconnect WebSocket when not needed
  • Prevent memory leaks in SPAs

4. Reconnection Strategyโ€‹

Implement automatic reconnection with exponential backoff:

Best practices:

  • Use exponential backoff for reconnection
  • Limit maximum reconnection attempts
  • Reset counters on successful connection
  • Allow manual disconnect without reconnection

5. Event Payload Structureโ€‹

Event payloads follow consistent structure:

Best practices:

  • Validate event payload structure
  • Handle missing fields gracefully
  • Type-check payload in TypeScript

6. Error Handlingโ€‹

Implement comprehensive error handling:

Best practices:

  • Catch errors in event handlers
  • Log errors for debugging
  • Show user-friendly error messages
  • Don't let errors crash application

7. Performance Optimizationโ€‹

Optimize WebSocket performance:

Best practices:

  • Throttle high-frequency events
  • Batch multiple updates together
  • Debounce UI updates
  • Avoid expensive operations in handlers

๐Ÿ“Š Quick Reference Tableโ€‹

MethodDescriptionReturnsUse Case
connect()Connect to WebSocket servervoidEstablish connection

๐Ÿ’ก Important Notesโ€‹

โš ๏ธ Connection State Managementโ€‹

Always check connection state before subscribing

๐Ÿ”„ Reconnection Handlingโ€‹

WebSocket connections can drop unexpectedly:

  • Network changes (WiFi to cellular)
  • Server restarts
  • Idle timeout

Always implement reconnection logic

๐Ÿงน Memory Leak Preventionโ€‹

Unsubscribe when done to prevent memory leaks

๐Ÿ”’ Securityโ€‹

WebSocket connections are authenticated:

  • Token-based authentication (same as REST API)
  • Secure WebSocket (WSS) protocol
  • No need to send token with each message

Best practices:

  • Use WSS (secure WebSocket) in production
  • Don't expose sensitive data in event handlers
  • Validate event payloads before processing

๐Ÿ“ฑ Mobile Considerationsโ€‹

WebSocket on mobile devices:

  • Battery usage (efficient, but persistent connection)
  • Background connections may be terminated
  • Network changes require reconnection

Best practices:

  • Reconnect when app comes to foreground
  • Handle network state changes
  • Consider polling for non-critical updates on mobile

๐ŸŽ“ Best Practicesโ€‹

โœ… DO:โ€‹

  1. Check connection state - Subscribe only after connection opens
  2. Implement reconnection - Auto-reconnect on disconnect with exponential backoff
  3. Unsubscribe on cleanup - Prevent memory leaks in SPAs
  4. Handle errors gracefully - Catch errors in event handlers
  5. Throttle high-frequency events - Avoid overwhelming UI with updates
  6. Validate event payloads - Check data structure before processing
  7. Use named callbacks - Easier to unsubscribe and debug
  8. Log connection state - Track open/close/error events for debugging

โŒ DON'T:โ€‹

  1. Don't subscribe before connection - Wait for onOpen callback
  2. Don't forget to disconnect - Close connection when done
  3. Don't subscribe multiple times - Check if already subscribed
  4. Don't ignore reconnection - Connection can drop unexpectedly
  5. Don't expose sensitive data - Validate and sanitize event data
  6. Don't block event handlers - Keep handlers fast and async
  7. Don't forget error handling - Always handle WebSocket errors
  8. Don't skip unsubscription - Memory leaks in long-running apps

More information about the module's user interface https://doc.oneentry.cloud/docs/events/introduction

Definition of the WS moduleโ€‹

You can subscribe to events via the WebSocket to receive notifications


const { WS } = defineOneEntry(
"your-project-url", {
"token": "your-app-token"
}
);