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โ
| Feature | WebSocket | HTTP Polling |
|---|---|---|
| Connection | Persistent (stays open) | Repeated connections |
| Latency | Sub-second | Depends on interval (2-30s) |
| Efficiency | Very efficient | Wasteful (many empty responses) |
| Server Load | Low (events only) | High (constant requests) |
| Battery Usage | Low | High (mobile devices) |
| Use Case | Real-time updates | Acceptable 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 Type | Description | Example Use Case |
|---|---|---|
| order.created | New order placed | Show "New Order!" notification |
| order.updated | Order status changed | Update order status in UI |
| content.published | New content published | Refresh content list |
| content.updated | Content edited | Update displayed content |
| user.registered | New user signed up | Show new user in admin dashboard |
| payment.completed | Payment processed | Update order status to "Paid" |
| product.outOfStock | Product out of stock | Show "Out of Stock" badge |
Why Use WebSocket Module?โ
| Benefit | Description |
|---|---|
| Real-Time Updates | Instant notifications, no polling delay |
| Efficient | Single connection, low overhead |
| Battery Friendly | No constant polling on mobile |
| Scalable | Server pushes only when needed |
| Event-Driven | Subscribe to specific events |
| Live Features | Enable 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โ
| Method | Description | Returns | Use Case |
|---|---|---|---|
connect() | Connect to WebSocket server | void | Establish 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:โ
- Check connection state - Subscribe only after connection opens
- Implement reconnection - Auto-reconnect on disconnect with exponential backoff
- Unsubscribe on cleanup - Prevent memory leaks in SPAs
- Handle errors gracefully - Catch errors in event handlers
- Throttle high-frequency events - Avoid overwhelming UI with updates
- Validate event payloads - Check data structure before processing
- Use named callbacks - Easier to unsubscribe and debug
- Log connection state - Track open/close/error events for debugging
โ DON'T:โ
- Don't subscribe before connection - Wait for onOpen callback
- Don't forget to disconnect - Close connection when done
- Don't subscribe multiple times - Check if already subscribed
- Don't ignore reconnection - Connection can drop unexpectedly
- Don't expose sensitive data - Validate and sanitize event data
- Don't block event handlers - Keep handlers fast and async
- Don't forget error handling - Always handle WebSocket errors
- 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" });
๐ Related Documentationโ
- Orders Module - Order events for real-time order tracking
- Users Module - User events for registration notifications
- Payments Module - Payment events for transaction updates
- WebSocket API