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โ
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
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
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
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
Event Payload Structureโ
Event payloads follow consistent structure:
Best practices:
- Validate event payload structure
- Handle missing fields gracefully
- Type-check payload in TypeScript
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
Performance Optimizationโ
Optimize WebSocket performance:
Best practices:
- Throttle high-frequency events
- Batch multiple updates together
- Debounce UI updates
- Avoid expensive operations in handlers
๐ก 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
๐ Quick Reference Tableโ
| Method | Description | Use Case |
|---|---|---|
| connect() | Connect to WebSocket server | Establish connection |
โ Common Questions (FAQ)โ
How do I connect to the WebSocket server?โ
Use WS.connect() to establish a connection. Wait for the connection to open (listen for the onOpen event) before subscribing to events. The connection is authenticated using your app token from defineOneEntry().
What events can I subscribe to?โ
Subscribe to events like order.created, order.updated, content.published, payment.completed, user.registered, etc. The available events depend on your OneEntry configuration and the Events module setup in the admin panel.
How do I handle connection drops?โ
Implement automatic reconnection with exponential backoff. Listen for onClose and onError events, then attempt to reconnect after a delay (e.g., 1s, 2s, 4s, 8s, up to max 30s). Reset the delay counter on successful connection.
Should I use WebSocket or polling for my app?โ
Use WebSocket for real-time features (live chat, notifications, dashboards) where instant updates matter. Use polling for non-critical updates or when WebSocket connections are problematic (restrictive firewalls, mobile background mode).
How do I prevent memory leaks with WebSocket subscriptions?โ
Always unsubscribe from events when components unmount or when the connection is no longer needed. In React, use cleanup functions in useEffect. In Vue, use beforeUnmount lifecycle hook.
Can I use WebSocket on mobile devices?โ
Yes, but be aware that mobile OS may terminate background WebSocket connections. Reconnect when the app returns to the foreground. Consider the battery impact of persistent connections on mobile devices.
๐ Best Practicesโ
- 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
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