Ana içeriğe geç

Introduction

Open a real-time WebSocket connection to receive content, order, and user updates without polling.

More information about the module's user interface https://doc.oneentry.cloud/docs/events/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'
});

// connect() returns a socket.io Socket (requires an authorized user)
const socket = await WS.connect();

// Listen for events with socket.on(...)
socket.on('my_event', (payload) => {
console.log('Update received!', payload);
// Instant notification, no polling!
});

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 - Listen to events with socket.on(...)
  • 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 opens a connection
(const socket = await WS.connect())

2. Connection established
(socket.on('connect', ...) fires)

3. Client listens for events
(socket.on('my_event', 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
(socket.disconnect())

What events arrive over the connection

There is no fixed catalog of SDK event names. Events fire according to your Events module configuration in the admin panel (the event must have the WebSocket option enabled). You listen for an event by its marker with socket.on('<event_marker>', callback).

The payload depends on the event's source. Typical payload fields (see connect() for full examples):

Payload fieldArrives forContains
attributesEvery eventThe event's own attributes
productCatalog (product) eventsProduct attributes plus title
userUser-form eventsFields from the user form
orderOrder eventsOrder id and attributes
email / codeRegistration / code formsAdditional form fields

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

📋 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

MethodDescriptionUse Case
connect()Connect to WebSocket serverEstablish connection

🔐 connect() requires an authorized user — authenticate first via AuthProvider. After connecting, attach event handlers with socket.on(...).

❓ Common Questions (FAQ)

How do I connect to the WebSocket server?

Use WS.connect() to open a connection — it returns a socket.io Socket. It requires an authorized user, so call AuthProvider.auth(...) first. Wait for the connect event before relying on the socket, then attach handlers with socket.on('<event_marker>', callback). The connection is authenticated with the user's access token plus your app token from defineOneEntry().


What events can I subscribe to?

There is no fixed SDK event list. Events are defined by your Events module configuration in the admin panel (with the WebSocket option enabled), and you listen for an event by its marker with socket.on('<event_marker>', callback). See connect() for payload examples (product, user, order, form).


How do I handle connection drops?

Implement automatic reconnection with exponential backoff. Listen for the socket.io disconnect and connect_error events, then attempt to reconnect after a delay (e.g., 1s, 2s, 4s, 8s, up to max 30s). Reset the delay counter on a successful connect. (socket.io also reconnects automatically by default.)


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 - Detach handlers (socket.off) and socket.disconnect() to 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

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"
}
);