Node SDK
Full Documentation
This is the client SDK for EnSync engine (message delivery engine) that enables you to build an ecosystem of connected devices and services.Installation
Usage
Importing
Default (gRPC)
- Production URLs automatically use secure TLS (port 443)
localhostautomatically uses insecure connection (port 50051)- Explicit protocols:
grpcs://(secure) orgrpc://(insecure) - Custom ports:
node.gms.ensync.cloud:9090
API Reference
EnSyncEngine (gRPC - Default)
The main class that manages gRPC connections and client creation for the EnSync system. This is the default and recommended client for production use.EnSyncWebSocketEngine (WebSocket - Alternative)
An alternative class that manages WebSocket connections and client creation for the EnSync system.Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
url | string | Yes | The URL of the EnSync server |
options | object | No | Configuration options |
| Option | Type | Default | Description |
|---|---|---|---|
heartbeatInterval | number | 30000 | Heartbeat interval in ms (gRPC) |
pingInterval | number | 30000 | Ping interval in ms (WebSocket) |
reconnectInterval | number | 5000 | Reconnection interval in ms |
maxReconnectAttempts | number | 5 | Maximum reconnection attempts |
enableLogging | boolean | false | Enable/disable SDK console logs |
Creating a Client
- Initialize the engine with your server URL
- Create a client with your app key
Client Creation Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
appKey | string | Yes | Your EnSync application key |
options | object | No | Client configuration options |
| Option | Type | Default | Description |
|---|---|---|---|
appSecretKey | string | null | Default key used to decrypt incoming messages |
Client Returns
Returns a newEnSyncClient instance
Publishing Events
Publish Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
eventName | string | Yes | Name of the event (e.g., “company/service/event-type”) |
recipients | string[] | Yes | Array of appIds (the appIds of receiving parties) |
payload | object | Yes | Your event data (any JSON-serializable object) |
metadata | object | No | Control event persistence and add custom headers |
| Option | Type | Default | Description |
|---|---|---|---|
persist | boolean | false | Whether to persist the event on the server |
headers | object | {} | Custom headers to include with the event |
Subscribing to Events
Subscribe Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
eventName | string | Yes | Name of the event to subscribe to |
options | object | No | Subscription options |
| Option | Type | Default | Description |
|---|---|---|---|
autoAck | boolean | true | Set to false for manual acknowledgment |
appSecretKey | string | null | Custom decryption key for this subscription |
Subscription Methods
Event Structure
When you receive an event through a subscription handler, it contains:Closing Connections
Error Handling
The SDK throwsEnSyncError for various error conditions. Always wrap your code in try-catch blocks to handle potential errors gracefully.
| Error Type | Description |
|---|---|
EnSyncConnectionError | Connection or authentication issues |
EnSyncPublishError | Problems publishing events |
EnSyncSubscriptionError | Subscription-related errors |
EnSyncGenericError | Other errors |
Debugging with Logs
Enable SDK logging to get detailed information about errors:Complete Examples
Quick Start (gRPC - Default)
Note: This example uses environment variables for security. Create a.envfile with:
Quick Start (WebSocket)
Publishing Example
Subscribing Example
Best Practices
Connection Management
- Store connection credentials securely using environment variables
- Implement proper reconnection logic for production environments
- Always close connections when they’re no longer needed
Event Design
- Use hierarchical event names (e.g.,
domain/entity/action) - Keep payloads concise and well-structured
- Consider versioning your event schemas
Security Best Practices
- Never hardcode app keys or secret keys
- Use environment variables or secure key management solutions
- Implement proper authentication and authorization
- Consider encrypting sensitive payloads
Performance Optimization
- Batch events when possible instead of sending many small messages
- Consider message size and frequency in high-volume scenarios
- Use appropriate TTL values for your use case
- Implement proper error handling and retry logic
Subscription Control
The SDK provides methods to pause, continue, and replay events, which is useful for managing event processing flow.What Pause and Continue Do
When you create a client usingengine.createClient(), that client receives a unique clientId. This clientId (not the appKey) identifies your specific client instance on the EnSync server.
-
Pause: Temporarily stops the client from receiving new events from the server. The subscription remains active on the server, but events are not delivered to this specific client instance. Other clients with the same
appKeybut differentclientIdwill continue receiving events normally. - Continue: Resumes event delivery to the paused client. Any events that occurred during the pause (depending on server settings and TTL) may be delivered once the subscription is continued.
Replaying Events
The replay command allows you to request a specific event to be sent again, even if it has already been processed. Unlike regular event handling which delivers events through the.on handler, the replay function returns the event data directly to your code. This is useful for:
- Retrieving specific events for analysis or debugging
- Accessing historical event data without setting up a handler
- Examining event content without processing it
- Getting event data synchronously in your code flow
Deferring Events
The defer method allows you to postpone processing of an event for a specified period. This is useful when:- You need more time to prepare resources for processing
- You want to implement a retry mechanism with increasing delays
- You need to wait for another system to be ready
- You want to implement rate limiting for event processing
Discarding Events
The discard method allows you to permanently reject an event without processing it. This is useful when:- The event contains invalid or corrupted data
- The event is no longer relevant or has expired
- The event was sent to the wrong recipient
- You want to implement a filtering mechanism
- Temporary maintenance or system updates
- Rate limiting or throttling event processing
- Implementing backpressure mechanisms
- Batch processing of events
Implementation Details
- Pause/continue operations are performed at the subscription level, not the client level
- The server maintains the subscription state even when paused
- Pausing affects only the specific subscription instance, not all subscriptions for the client
- Events that arrive during a pause may be delivered when continued (depending on TTL settings)
- The pause state is not persisted across client restarts or reconnections