{"id":19339719,"url":"https://github.com/rubenv/node-broadcast-hub","last_synced_at":"2025-04-23T02:30:53.854Z","repository":{"id":10813517,"uuid":"13088073","full_name":"rubenv/node-broadcast-hub","owner":"rubenv","description":"WebSockets backed by Redis pubsub.","archived":false,"fork":false,"pushed_at":"2015-02-27T08:10:11.000Z","size":403,"stargazers_count":18,"open_issues_count":1,"forks_count":10,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-10T07:03:21.127Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"CoffeeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rubenv.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-09-25T08:19:51.000Z","updated_at":"2023-05-26T07:00:56.000Z","dependencies_parsed_at":"2022-08-29T15:00:36.704Z","dependency_job_id":null,"html_url":"https://github.com/rubenv/node-broadcast-hub","commit_stats":null,"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubenv%2Fnode-broadcast-hub","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubenv%2Fnode-broadcast-hub/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubenv%2Fnode-broadcast-hub/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubenv%2Fnode-broadcast-hub/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rubenv","download_url":"https://codeload.github.com/rubenv/node-broadcast-hub/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250357566,"owners_count":21417307,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-10T03:23:30.070Z","updated_at":"2025-04-23T02:30:53.571Z","avatar_url":"https://github.com/rubenv.png","language":"CoffeeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# broadcast-hub - WebSockets backed by Redis pubsub.\n\n\u003e Exposes redis pubsub channels over websockets.\n\n[![Build Status](https://travis-ci.org/rubenv/node-broadcast-hub.png?branch=master)](https://travis-ci.org/rubenv/node-broadcast-hub)\n\n## Introduction\n\nThe broadcast-hub module provides easy-to-use middleware for adding real-time notifications to your web applications. It is intended to be both easy to integrate (low effort) yet scalable.\n\nThe hub consists of a number of broadcast channels to which clients can subscribe. Once subscribed, they'll receive any message posted to that channel.\n\nWhat it does:\n\n* Provide the needed Websocket handling (based on [sockjs](http://sockjs.org/)).\n* Provides a client-side library for subscribing to broadcast channels.\n* Uses [redis](http://redis.io/) as a pubsub mechanism to achieve scalability.\n* Allows authenticating clients and individual channels.\n* Automatic connection handling (including reconnecting on connection loss).\n\n## Getting started\n### Requirements\nYou'll need a redis server on the backend. Redis takes care of all the message routing, broadcast-hub simply publishes those messages over websockets.\n\n### Server-side\nAdd broadcast-hub to your project (backend components):\n\n```\nnpm install --save broadcast-hub\n```\n\nYou'll need to setup a broadcast-hub on the server. This can be a standalone component or part of your existing Node.JS backend.\n\nIf you are using [Express](http://expressjs.com/):\n\n```js\nvar express = require('express');\nvar broadcastHub = require('broadcast-hub');\n\nvar app = express();\n// Do Express configuration\nvar server = app.listen(3000);      // (1)\nbroadcastHub.listen(server);        // (2)\n```\n\n1. When you call `app.listen`, the return value will be a `http.Server`, store this in a variable.\n2. Pass the `http.Server` to broadcast-hub. This will set up the needed sockjs listeners.\n\nA full example can be found in `example/server.js`.\n\n### Client-side\nAdd broadcast-hub to your project (client-side components):\n\n```\nbower install --save broadcast-hub\n```\n\nAdd the socketjs and broadcast-hub libraries to your app:\n\n```html\n\u003chead\u003e\n    \u003c!-- More stuff here --\u003e\n    \u003cscript src=\"bower_components/sockjs/sockjs.min.js\"\u003e\u003c/script\u003e\n    \u003cscript src=\"bower_components/broadcast-hub/broadcast-hub-client.min.js\"\u003e\u003c/script\u003e\n\u003c/head\u003e\n```\n\nThen, in your client-side JavaScript, connect to the hub and subscribe to some channels:\n\n```js\nvar client = new BroadcastHubClient();\nclient.subscribe('test');\nclient.on('message:test', function (message) {\n\tconsole.log(message);\n})\n```\n\nAll received messages in the `test` channel will be output to the console.\n\n#### Client options\nYou can optionally pass an options object to the client:\n\n```js\nvar client = new BroadcastHubClient({\n    /* Options here */\n});\n```\n\n##### `auth`\n**Type:** `object`\n\nAny data that should be passed to the `canConnect` function on the backend, as the `data` argument.\n\n##### `server`\n**Type:** `string`\n\nThe URL on which the client should connect.\n\n\n### Publishing messages\nUsing any redis client, publish a message on the same channel and it'll get relayed to the clients.\n\nFor instance, using the `redis-cli` client:\n\n```\n$ redis-cli \nredis 127.0.0.1:6379\u003e publish test \"Test message\"\n```\n\nThis will result in `Test message` showing up in the browser console.\n\nThere are no special requirements for publishing messages, so you can use any redis client for publishing, such as [node-redis (Node.JS)](https://github.com/mranney/node_redis) or [predis (PHP)](https://github.com/nrk/predis). This is by design: it should be as trivial as possible to publish messages.\n\nFrom Node.JS, use something like this:\n\n```js\nvar redis = require('redis');\nvar client = redis.createClient();\nclient.publish('test', 'Test message');\n```\n\nThere's also a convenience method defined on the hub object that's returned when calling `listen`:\n\n```js\nvar hub = broadcastHub.listen(server);\nhub.publish('test', 'Test message');\n```\n\nYou can optionally pass a completion callback as the third argument to this function.\n\n## Scalability\nThe architecture of broadcast-hub is deliberatly kept simple to make scaling possible.\n\nPubSub is delegate to Redis. Node.JS makes one Redis connection per subscribed channel. This allows fast broadcasting among clients.\n\nIf you start to run into the limits of Node.JS:\n\n* Add more Node.JS instances to which clients can connect.\n* Use a load balancer to spread clients across these backends instances.\n* There is no requirement for pinning clients to backend instances. Clients will automatically reconnect if one of the backends goes down and restore all subscriptions. This should be transparent.\n\nIf you start to run into the limits of redis:\n\n* Use [master/slave replication](http://redis.io/topics/replication) to add more redis tiers.\n\nBe sure to have sufficiently high connection limits set up. You'll need N+M TCP connections (where N is the number of connected clients and M is the number of subscribed channels in total [1]).\n\nAdd another TCP connection per client if you have nginx or haproxy as a reverse-proxy (not strictly needed, though recommended to offload compression and encryption).\n\n[1] Two clients connecting to the same channel will only result in one connection to Redis.\n\n## Configuration\nYou can pass an options object to the `listen` call:\n\n```js\nbroadcastHub.listen(server, {\n    /* Options here */\n});\n```\n\n### `canConnect`\n**Type:** `function (client, data, cb)`\n\nA function that can be used to determine whether or not the connecting client is allowed to connect to the broadcast hub. The passed `data` object is supplied by the client and can be configured using the `auth` option on the client.\n\nThe result of this authorization check should be passed to the callback `cb`: This function takes two arguments: an error or a boolean value.\n\nExample:\n\n```js\nbroadcastHub.listen(server, {\n\tcanConnect: function (client, data, cb) {\n\t    // Do some database lookups here\n\t    cb(null, true);\n\t}    \n});\n```\n\nYou can store data associated to a client in the `client.data` field.\n\nExample:\n\n```js\n\tcanConnect: function (client, data, cb) {\n\t    // Look up client information\n\t    client.data.user = user;\n\t    cb(null, true);\n\t}    \n```\n\nThis data will then be accessible in `canSubscribe`.\n\n\n### `canSubscribe`\n**Type:** `function (client, channel, cb)`\n\nSimilar to `canConnect`, except that this function decides whether or not the client can subscribe to the requested channel.\n\n### `prefix`\n**Type:** `string`\n\nThe URL path on which the socket handlers should be installed. Defaults to `/sockets`.\n\n### `redisHost`\n**Type:** `string` (default: `127.0.0.1`)\n\nThe hostname of the redis server used for subscriptions.\n\n### `redisPort`\n**Type:** `int` (default: `6379`)\n\nThe port of the redis server used for subscriptions.\n\n### `redisAuth`\n**Type:** `string` (default: `null`)\n\nPassed to ``redis.auth`` after the subscription client is created, useful on heroku when auth is required\n\n### `publishHost`\n**Type:** `string` (default: `options.redisHost`)\n\nThe hostname of the redis server used for publishing messages (may be different if you use master/server replication).\n\n### `publishPort`\n**Type:** `int` (default: `options.publishPort`)\n\nThe port of the redis server used for publishing.\n\n### `publishAuth`\n**Type:** `string` (default: `null`)\n\nPassed to ``redis.auth`` after the publishing client is created, useful on heroku when auth is required\n\n## Contributing\nAll code lives in the `src` folder and is written in CoffeeScript. Try to stick to the style conventions used in existing code.\n\nTests can be run using `grunt test`. A convenience command to automatically run the tests is also available: `grunt watch`. Please add test cases when adding new functionality: this will prove that it works and ensure that it will keep working in the future.\n\n    \n## License \n\n    (The MIT License)\n\n    Copyright (C) 2013 by Ruben Vermeersch \u003cruben@savanne.be\u003e\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n    THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frubenv%2Fnode-broadcast-hub","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frubenv%2Fnode-broadcast-hub","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frubenv%2Fnode-broadcast-hub/lists"}