Skip to content

Node.js quick start

To publish an event to your Node.js app using Jetsocket.io, follow this guide.

First, install the Jetsocket Node.js library:

Terminal window
npm install jetsocket

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 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 to receive events:

const channel = jetsocket.subscribe("my-channel");

Bind to events on the channel:

channel.bind("my-event", (data) => {
console.log("Received event:", data);
});

Send events to the channel:

jetsocket.trigger("my-channel", "my-event", { message: "hello world" });

Here’s a complete example that demonstrates the full flow:

const Jetsocket = require("jetsocket");
// Initialize Jetsocket
const jetsocket = new Jetsocket({
appId: "APP_ID",
key: "APP_KEY",
secret: "APP_SECRET",
cluster: "APP_CLUSTER",
});
// Subscribe to a channel
const channel = jetsocket.subscribe("my-channel");
// Listen for events
channel.bind("my-event", (data) => {
console.log("Received:", data.message);
});
// Trigger an event
setTimeout(() => {
jetsocket.trigger("my-channel", "my-event", { message: "Hello from Node.js!" });
}, 1000);

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

Now that you have the basics working, explore more advanced features like private channels, presence channels, and authentication.