Node.js SDK
Node.js SDK
Section titled “Node.js SDK”The Jetsocket Node.js library allows you to trigger events and manage your Jetsocket app from your Node.js server.
Installation
Section titled “Installation”npm install jetsocketBasic Usage
Section titled “Basic Usage”const Jetsocket = require("jetsocket");
const jetsocket = new Jetsocket({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER",});
// Trigger an eventjetsocket.trigger("my-channel", "my-event", { message: "Hello world!" });Configuration
Section titled “Configuration”const jetsocket = new Jetsocket({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER", useTLS: true, encryptionMasterKey: "your-encryption-key", // For encrypted channels host: "api.jetsocket.io", port: 443, timeout: 30000, keepAlive: true, keepAliveMsecs: 1000, maxSockets: 100, maxFreeSockets: 10, freeSocketKeepAliveTimeout: 30000,});Configuration Options
Section titled “Configuration Options”| Parameter | Type | Default | Description |
|---|---|---|---|
appId | String | - | Your Jetsocket app ID |
key | String | - | Your Jetsocket app key |
secret | String | - | Your Jetsocket app secret |
cluster | String | - | Your Jetsocket cluster |
useTLS | Boolean | true | Use TLS for connections |
encryptionMasterKey | String | - | Master key for encrypted channels |
host | String | api.jetsocket.io | Jetsocket API host |
port | Number | 443 | Jetsocket API port |
timeout | Number | 30000 | Request timeout |
keepAlive | Boolean | true | Enable keep-alive |
maxSockets | Number | 100 | Maximum number of sockets |
Triggering Events
Section titled “Triggering Events”Basic Event Triggering
Section titled “Basic Event Triggering”jetsocket.trigger("my-channel", "my-event", { message: "Hello world!" });Triggering to Multiple Channels
Section titled “Triggering to Multiple Channels”jetsocket.trigger(["channel-1", "channel-2"], "my-event", { message: "Hello world!" });Triggering with Socket ID Exclusion
Section titled “Triggering with Socket ID Exclusion”jetsocket.trigger("my-channel", "my-event", { message: "Hello world!" }, { socket_id: "123.456"});Triggering to Users
Section titled “Triggering to Users”jetsocket.triggerToUser("user-123", "my-event", { message: "Hello user!" });Triggering to Multiple Users
Section titled “Triggering to Multiple Users”jetsocket.triggerToUsers(["user-123", "user-456"], "my-event", { message: "Hello users!" });Channel Authorization
Section titled “Channel Authorization”Basic Authorization
Section titled “Basic Authorization”const express = require("express");const Jetsocket = require("jetsocket");
const app = express();app.use(express.json());
const jetsocket = new Jetsocket({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER",});
app.post("/jetsocket/auth", (req, res) => { const socketId = req.body.socket_id; const channel = req.body.channel_name;
// Verify the user can access this channel if (canAccessChannel(req.user, channel)) { const authResponse = jetsocket.authorizeChannel(socketId, channel); res.send(authResponse); } else { res.status(403).send("Forbidden"); }});
function canAccessChannel(user, channel) { // Your authorization logic here if (channel.startsWith("private-user-")) { const userId = channel.replace("private-user-", ""); return user.id === userId; } return false;}Authorization with User Data
Section titled “Authorization with User Data”app.post("/jetsocket/auth", (req, res) => { const socketId = req.body.socket_id; const channel = req.body.channel_name; const user = req.user;
if (canAccessChannel(user, channel)) { const authResponse = jetsocket.authorizeChannel(socketId, channel, { user_id: user.id, user_info: { name: user.name, email: user.email } }); res.send(authResponse); } else { res.status(403).send("Forbidden"); }});User Authentication
Section titled “User Authentication”Basic User Authentication
Section titled “Basic User Authentication”app.post("/jetsocket/user-auth", (req, res) => { const socketId = req.body.socket_id; const user = req.user;
const authResponse = jetsocket.authenticateUser(socketId, { user_id: user.id, user_info: { name: user.name, email: user.email } });
res.send(authResponse);});Webhooks
Section titled “Webhooks”Webhook Verification
Section titled “Webhook Verification”app.post("/jetsocket/webhook", (req, res) => { const webhook = jetsocket.webhook(req);
if (webhook.isValid()) { // Process webhook events webhook.getEvents().forEach(event => { console.log("Webhook event:", event.name, event.data); });
res.status(200).send("OK"); } else { res.status(400).send("Invalid webhook"); }});Webhook Configuration
Section titled “Webhook Configuration”const webhook = jetsocket.webhook(req, { webhookSecret: "your-webhook-secret"});Channel Information
Section titled “Channel Information”Getting Channel Information
Section titled “Getting Channel Information”// Get channel infojetsocket.getChannelInfo("my-channel").then(info => { console.log("Channel info:", info);});
// Get channel with user countjetsocket.getChannelInfo("presence-my-channel", { info: "user_count" }).then(info => { console.log("User count:", info.user_count);});Getting All Channels
Section titled “Getting All Channels”jetsocket.getChannels().then(channels => { console.log("All channels:", channels);});
// Get channels with filtersjetsocket.getChannels({ prefix: "private-", info: "user_count"}).then(channels => { console.log("Private channels:", channels);});User Management
Section titled “User Management”Getting User Information
Section titled “Getting User Information”jetsocket.getUserInfo("user-123").then(user => { console.log("User info:", user);});Getting All Users
Section titled “Getting All Users”jetsocket.getUsers().then(users => { console.log("All users:", users);});Terminating User Connections
Section titled “Terminating User Connections”jetsocket.terminateUserConnections("user-123").then(() => { console.log("User connections terminated");});Error Handling
Section titled “Error Handling”Promise-based Error Handling
Section titled “Promise-based Error Handling”jetsocket.trigger("my-channel", "my-event", { message: "Hello" }) .then(response => { console.log("Event triggered successfully:", response); }) .catch(error => { console.error("Error triggering event:", error); });Async/Await Error Handling
Section titled “Async/Await Error Handling”async function triggerEvent() { try { const response = await jetsocket.trigger("my-channel", "my-event", { message: "Hello" }); console.log("Event triggered successfully:", response); } catch (error) { console.error("Error triggering event:", error); }}Express.js Integration
Section titled “Express.js Integration”Complete Express.js Example
Section titled “Complete Express.js Example”const express = require("express");const Jetsocket = require("jetsocket");
const app = express();app.use(express.json());
const jetsocket = new Jetsocket({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER",});
// Middleware to authenticate usersconst authenticateUser = (req, res, next) => { const token = req.headers.authorization; if (token) { req.user = verifyToken(token); next(); } else { res.status(401).send("Unauthorized"); }};
// Channel authorizationapp.post("/jetsocket/auth", authenticateUser, (req, res) => { const socketId = req.body.socket_id; const channel = req.body.channel_name; const user = req.user;
if (canAccessChannel(user, channel)) { const authResponse = jetsocket.authorizeChannel(socketId, channel); res.send(authResponse); } else { res.status(403).send("Forbidden"); }});
// User authenticationapp.post("/jetsocket/user-auth", authenticateUser, (req, res) => { const socketId = req.body.socket_id; const user = req.user;
const authResponse = jetsocket.authenticateUser(socketId, { user_id: user.id, user_info: { name: user.name, email: user.email } });
res.send(authResponse);});
// Trigger eventsapp.post("/trigger", authenticateUser, async (req, res) => { try { const { channel, event, data } = req.body; await jetsocket.trigger(channel, event, data); res.json({ success: true }); } catch (error) { console.error("Error triggering event:", error); res.status(500).json({ error: "Failed to trigger event" }); }});
// Get channel infoapp.get("/channels/:channel", authenticateUser, async (req, res) => { try { const info = await jetsocket.getChannelInfo(req.params.channel); res.json(info); } catch (error) { console.error("Error getting channel info:", error); res.status(500).json({ error: "Failed to get channel info" }); }});
// Webhook endpointapp.post("/jetsocket/webhook", (req, res) => { const webhook = jetsocket.webhook(req);
if (webhook.isValid()) { webhook.getEvents().forEach(event => { console.log("Webhook event:", event.name, event.data); }); res.status(200).send("OK"); } else { res.status(400).send("Invalid webhook"); }});
function canAccessChannel(user, channel) { if (channel.startsWith("private-user-")) { const userId = channel.replace("private-user-", ""); return user.id === userId; }
if (channel === "private-admin-dashboard") { return user.role === "admin"; }
return false;}
app.listen(3000, () => { console.log("Server running on port 3000");});TypeScript Support
Section titled “TypeScript Support”import Jetsocket from 'jetsocket';
const jetsocket: Jetsocket = new Jetsocket({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER",});
interface MessageData { message: string; timestamp: string;}
async function sendMessage(channel: string, data: MessageData): Promise<void> { try { await jetsocket.trigger(channel, "new-message", data); } catch (error) { console.error("Failed to send message:", error); }}Best Practices
Section titled “Best Practices”Error Handling
Section titled “Error Handling”// Always handle errorsjetsocket.trigger("my-channel", "my-event", data) .catch(error => { console.error("Failed to trigger event:", error); // Implement retry logic or fallback });Rate Limiting
Section titled “Rate Limiting”const rateLimit = require("express-rate-limit");
const triggerLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100 // limit each IP to 100 requests per windowMs});
app.post("/trigger", triggerLimiter, (req, res) => { // Your trigger logic});Logging
Section titled “Logging”// Log all events for debuggingapp.post("/trigger", (req, res) => { const { channel, event, data } = req.body;
console.log(`Triggering event ${event} on channel ${channel}:`, data);
jetsocket.trigger(channel, event, data) .then(() => { console.log(`Successfully triggered ${event} on ${channel}`); res.json({ success: true }); }) .catch(error => { console.error(`Failed to trigger ${event} on ${channel}:`, error); res.status(500).json({ error: "Failed to trigger event" }); });});Next Steps
Section titled “Next Steps”- Learn about channels and different channel types
- Explore authentication for secure applications
- Check out webhooks for real-time notifications
- See examples for complete application patterns