Node.js quick start
Node.js quick start
Section titled “Node.js quick start”To publish an event to your Node.js app using Jetsocket.io, follow this guide.
Install the Jetsocket library
Section titled “Install the Jetsocket library”First, install the Jetsocket Node.js library:
npm install jetsocketGet your API keys
Section titled “Get your API keys”Create an account and then create a Jetsocket app. To get API keys, from the Jetsocket Dashboard, navigate to App Keys. Copy your app_id, key, secret, and cluster.
Initialize Jetsocket
Section titled “Initialize Jetsocket”Initialize Jetsocket with your credentials:
const Jetsocket = require("jetsocket");
const jetsocket = new Jetsocket({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER",});Subscribe to a channel
Section titled “Subscribe to a channel”Subscribe to a channel to receive events:
const channel = jetsocket.subscribe("my-channel");Listen for events
Section titled “Listen for events”Bind to events on the channel:
channel.bind("my-event", (data) => { console.log("Received event:", data);});Trigger events
Section titled “Trigger events”Send events to the channel:
jetsocket.trigger("my-channel", "my-event", { message: "hello world" });Complete example
Section titled “Complete example”Here’s a complete example that demonstrates the full flow:
const Jetsocket = require("jetsocket");
// Initialize Jetsocketconst jetsocket = new Jetsocket({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER",});
// Subscribe to a channelconst channel = jetsocket.subscribe("my-channel");
// Listen for eventschannel.bind("my-event", (data) => { console.log("Received:", data.message);});
// Trigger an eventsetTimeout(() => { jetsocket.trigger("my-channel", "my-event", { message: "Hello from Node.js!" });}, 1000);Express.js integration
Section titled “Express.js integration”Here’s how to integrate Jetsocket with an Express.js application:
const express = require("express");const Jetsocket = require("jetsocket");
const app = express();const jetsocket = new Jetsocket({ appId: "APP_ID", key: "APP_KEY", secret: "APP_SECRET", cluster: "APP_CLUSTER",});
app.post("/trigger", (req, res) => { jetsocket.trigger("my-channel", "my-event", { message: "Hello from Express!" }); res.json({ success: true });});
app.listen(3000, () => { console.log("Server running on port 3000");});Where next?
Section titled “Where next?”Now that you have the basics working, explore more advanced features like private channels, presence channels, and authentication.