{"id":24558132,"url":"https://github.com/rse/hapi-plugin-websocket","last_synced_at":"2025-04-03T02:10:56.393Z","repository":{"id":40063977,"uuid":"53799805","full_name":"rse/hapi-plugin-websocket","owner":"rse","description":"HAPI plugin for seamless WebSocket integration","archived":false,"fork":false,"pushed_at":"2024-09-11T05:39:58.000Z","size":103,"stargazers_count":53,"open_issues_count":9,"forks_count":12,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-26T19:11:09.316Z","etag":null,"topics":["hapi","hapi-plugin","websockets","ws"],"latest_commit_sha":null,"homepage":"http://npmjs.com/hapi-plugin-websocket","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rse.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-03-13T18:09:33.000Z","updated_at":"2024-09-11T05:39:59.000Z","dependencies_parsed_at":"2024-06-18T14:58:01.435Z","dependency_job_id":"80ac5feb-fe03-48e5-9a56-ec32839ac472","html_url":"https://github.com/rse/hapi-plugin-websocket","commit_stats":{"total_commits":232,"total_committers":4,"mean_commits":58.0,"dds":"0.025862068965517238","last_synced_commit":"7660fbe460d63687024b875657c3835997ea1c00"},"previous_names":[],"tags_count":89,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rse%2Fhapi-plugin-websocket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rse%2Fhapi-plugin-websocket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rse%2Fhapi-plugin-websocket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rse%2Fhapi-plugin-websocket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rse","download_url":"https://codeload.github.com/rse/hapi-plugin-websocket/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246922247,"owners_count":20855345,"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":["hapi","hapi-plugin","websockets","ws"],"created_at":"2025-01-23T05:47:28.094Z","updated_at":"2025-04-03T02:10:56.375Z","avatar_url":"https://github.com/rse.png","language":"JavaScript","readme":"\nhapi-plugin-websocket\n=====================\n\n[HAPI](http://hapijs.com/) plugin for seamless WebSocket integration.\n\n\u003cp/\u003e\n\u003cimg src=\"https://nodei.co/npm/hapi-plugin-websocket.png?downloads=true\u0026stars=true\" alt=\"\"/\u003e\n\n\u003cp/\u003e\n\u003cimg src=\"https://david-dm.org/rse/hapi-plugin-websocket.png\" alt=\"\"/\u003e\n\nInstallation\n------------\n\n```shell\n$ npm install hapi hapi-plugin-websocket\n```\n\nAbout\n-----\n\nThis is a small plugin for the [HAPI](http://hapijs.com/) server\nframework of [Node.js](https://nodejs.org/) for seamless\n[WebSocket](https://tools.ietf.org/html/rfc6455) protocol integration.\nIt accepts WebSocket connections and transforms between incoming/outgoing\nWebSocket messages and injected HTTP request/response messages.\n\nUsage\n-----\n\nThe following sample server shows all features at once:\n\n```js\nconst Boom          = require(\"@hapi/boom\")\nconst HAPI          = require(\"@hapi/hapi\")\nconst HAPIAuthBasic = require(\"@hapi/basic\")\nconst HAPIWebSocket = require(\"hapi-plugin-websocket\")\nconst WebSocket     = require(\"ws\")\n\n;(async () =\u003e {\n    /*  create new HAPI service  */\n    const server = new HAPI.Server({ address: \"127.0.0.1\", port: 12345 })\n\n    /*  register HAPI plugins  */\n    await server.register(HAPIWebSocket)\n    await server.register(HAPIAuthBasic)\n\n    /*  register Basic authentication strategy  */\n    server.auth.strategy(\"basic\", \"basic\", {\n        validate: async (request, username, password, h) =\u003e {\n            let isValid     = false\n            let credentials = null\n            if (username === \"foo\" \u0026\u0026 password === \"bar\") {\n                isValid = true\n                credentials = { username }\n            }\n            return { isValid, credentials }\n        }\n    })\n\n    /*  provide plain REST route  */\n    server.route({\n        method: \"POST\", path: \"/foo\",\n        config: {\n            payload: { output: \"data\", parse: true, allow: \"application/json\" }\n        },\n        handler: (request, h) =\u003e {\n            return { at: \"foo\", seen: request.payload }\n        }\n    })\n\n    /*  provide combined REST/WebSocket route  */\n    server.route({\n        method: \"POST\", path: \"/bar\",\n        config: {\n            payload: { output: \"data\", parse: true, allow: \"application/json\" },\n            plugins: { websocket: true }\n        },\n        handler: (request, h) =\u003e {\n            let { mode } = request.websocket()\n            return { at: \"bar\", mode: mode, seen: request.payload }\n        }\n    })\n\n    /*  provide exclusive WebSocket route  */\n    server.route({\n        method: \"POST\", path: \"/baz\",\n        config: {\n            plugins: { websocket: { only: true, autoping: 30 * 1000 } }\n        },\n        handler: (request, h) =\u003e {\n            return { at: \"baz\", seen: request.payload }\n        }\n    })\n\n    /*  provide full-featured exclusive WebSocket route  */\n    server.route({\n        method: \"POST\", path: \"/quux\",\n        config: {\n            response: { emptyStatusCode: 204 },\n            payload: { output: \"data\", parse: true, allow: \"application/json\" },\n            auth: { mode: \"required\", strategy: \"basic\" },\n            plugins: {\n                websocket: {\n                    only: true,\n                    initially: true,\n                    subprotocol: \"quux.example.com\",\n                    connect: ({ ctx, ws }) =\u003e {\n                        ctx.to = setInterval(() =\u003e {\n                            if (ws.readyState === WebSocket.OPEN)\n                                ws.send(JSON.stringify({ cmd: \"PING\" }))\n                        }, 5000)\n                    },\n                    disconnect: ({ ctx }) =\u003e {\n                        if (ctx.to !== null) {\n                            clearTimeout(this.ctx)\n                            ctx.to = null\n                        }\n                    }\n                }\n            }\n        },\n        handler: (request, h) =\u003e {\n            let { initially, ws } = request.websocket()\n            if (initially) {\n                ws.send(JSON.stringify({ cmd: \"HELLO\", arg: request.auth.credentials.username }))\n                return \"\"\n            }\n            if (typeof request.payload !== \"object\" || request.payload === null)\n                return Boom.badRequest(\"invalid request\")\n            if (typeof request.payload.cmd !== \"string\")\n                return Boom.badRequest(\"invalid request\")\n            if (request.payload.cmd === \"PING\")\n                return { result: \"PONG\" }\n            else if (request.payload.cmd === \"AWAKE-ALL\") {\n                var peers = request.websocket().peers\n                peers.forEach((peer) =\u003e {\n                    peer.send(JSON.stringify({ cmd: \"AWAKE\" }))\n                })\n                return \"\"\n            }\n            else\n                return Boom.badRequest(\"unknown command\")\n        }\n    })\n\n    /*  provide exclusive framed WebSocket route  */\n    server.route({\n        method: \"POST\", path: \"/framed\",\n        config: {\n            plugins: {\n                websocket: {\n                    only:          true,\n                    autoping:      30 * 1000,\n                    frame:         true,\n                    frameEncoding: \"json\",\n                    frameRequest:  \"REQUEST\",\n                    frameResponse: \"RESPONSE\"\n                }\n            }\n        },\n        handler: (request, h) =\u003e {\n            return { at: \"framed\", seen: request.payload }\n        }\n    })\n\n    /*  start the HAPI service  */\n    await server.start()\n})().catch((err) =\u003e {\n    console.log(`ERROR: ${err}`)\n})\n\n```\n\nYou can test-drive this the following way (with the help\nof [curl](https://curl.haxx.se/) and [wscat](https://www.npmjs.com/package/wscat)):\n\n```shell\n# start the sample server implementation (see source code above)\n$ node sample-server.js \u0026\n\n# access the plain REST route via REST\n$ curl -X POST --header 'Content-type: application/json' \\\n  --data '{ \"foo\": 42 }' http://127.0.0.1:12345/foo\n{\"at\":\"foo\",\"seen\":{\"foo\":42}}\n\n# access the combined REST/WebSocket route via REST\n$ curl -X POST --header 'Content-type: application/json' \\\n  --data '{ \"foo\": 42 }' http://127.0.0.1:12345/bar\n{\"at\":\"bar\",\"mode\":\"http\",\"seen\":{\"foo\":42}}\n\n# access the exclusive WebSocket route via REST\n$ curl -X POST --header 'Content-type: application/json' \\\n  --data '{ \"foo\": 42 }' http://127.0.0.1:12345/baz\n{\"statusCode\":400,\"error\":\"Bad Request\",\"message\":\"Plain HTTP request to a WebSocket-only route not allowed\"}\n\n# access the combined REST/WebSocket route via WebSocket\n$ wscat --connect ws://127.0.0.1:12345/bar\n\u003e { \"foo\": 42 }\n\u003c {\"at\":\"bar\",\"mode\":\"websocket\",\"seen\":{\"foo\":42}}\n\u003e { \"foo\": 7 }\n\u003c {\"at\":\"bar\",\"mode\":\"websocket\",\"seen\":{\"foo\":7}}\n\n# access the exclusive WebSocket route via WebSocket\n$ wscat --connect ws://127.0.0.1:12345/baz\n\u003e { \"foo\": 42 }\n\u003c {\"at\":\"baz\",\"seen\":{\"foo\":42}}\n\u003e { \"foo\": 7 }\n\u003c {\"at\":\"baz\",\"seen\":{\"foo\":7}}\n\n# access the full-featured exclusive WebSocket route via WebSockets\n$ wscat --subprotocol \"quux.example.com\" --auth foo:bar --connect ws://127.0.0.1:12345/quux\n\u003c {\"cmd\":\"HELLO\",arg:\"foo\"}\n\u003e {\"cmd\":\"PING\"}\n\u003c {\"result\":\"PONG\"}\n\u003e {\"cmd\":\"AWAKE-ALL\"}\n\u003c {\"cmd\":\"AWAKE\"}\n\u003c {\"cmd\":\"PING\"}\n\u003c {\"cmd\":\"PING\"}\n\u003c {\"cmd\":\"PING\"}\n\u003c {\"cmd\":\"PING\"}\n\n# access framed exclusive WebSocket route\n$ wscat --connect ws://127.0.0.1:12345/framed\n\u003c [ 42, 0, \"REQUEST\", { \"foo\": 7 } ]\n\u003e [1,42,\"RESPONSE\",{\"at\":\"framed\",\"seen\":{\"foo\":7}}]\n```\n\nApplication Programming Interface\n---------------------------------\n\n- **Import Module**:\n\n```js\nconst HAPIWebSocket = require(\"hapi-plugin-websocket\")\n```\n\n- **Register Module in HAPI** (simple variant):\n\n```js\nawait server.register(HAPIWebSocket)\n```\n\n- **Register Module in HAPI** (complex variant):\n\n```js\nserver.register({\n    plugin: HAPIWebSocket,\n    options: {\n        create: (wss) =\u003e {\n            ...\n        }\n    }\n})\n```\n\n- **Register WebSocket-enabled Route** (simple variant):\n\n```js\nserver.route({\n    method: \"POST\",\n    path: \"/foo\",\n    options: {\n        plugins: { websocket: true }\n    },\n    handler: async (request, h) =\u003e {\n        ...\n    }\n})\n```\n\n- **Register WebSocket-enabled Route** (complex variant):\n\n```js\nserver.route({\n    method: \"POST\",\n    path: \"/foo\",\n    options: {\n        plugins: {\n            websocket: {\n                only: true,\n                autoping: 10 * 1000,\n                subprotocol: \"quux.example.com\",\n                initially: true,\n                connect: ({ ctx, wss, ws, req, peers }) =\u003e {\n                    ...\n                    ws.send(...)\n                    ...\n                },\n                disconnect: ({ ctx, wss, ws, req, peers }) =\u003e {\n                    ...\n                }\n            }\n        }\n    },\n    handler: async (request, h) =\u003e {\n        let { mode, ctx, wss, ws, req, peers, initially } = request.websocket()\n        ...\n    }\n})\n```\n\n- **Register WebSocket-enabled Framed Route**:\n\n```js\nserver.route({\n    method: \"POST\",\n    path:   \"/foo\",\n    options: {\n        plugins: {\n            websocket: {\n                only:          true,\n                frame:         true,\n                frameEncoding: \"json\",\n                frameRequest:  \"REQUEST\",\n                frameResponse: \"RESPONSE\"\n            }\n        }\n    },\n    handler: async (request, h) =\u003e {\n        let { mode, ctx, wss, ws, wsf, req, peers, initially } = request.websocket()\n        ...\n    }\n})\n```\n\nNotice\n------\n\nWith [NES](https://github.com/hapijs/nes) there is a popular and elaborated alternative\nHAPI plugin for WebSocket integration. The `hapi-plugin-websocket`\nplugin in contrast is a light-weight solution and was developed\nwith especially six distinct features in mind:\n\n1. everything is handled through the regular HAPI route API\n   (i.e. no additional APIs like `server.subscribe()`),\n\n2. one can use HAPI route paths with arbitrary parameters,\n\n3. one can restrict a HAPI route to a particular WebSocket subprotocol,\n\n4. HTTP replies with status code 204 (\"No Content\") are explicitly taken\n   into account (i.e. no WebSocket response message is sent at all in\n   this case),\n\n5. HAPI routes can be controlled to be plain REST, combined REST+WebSocket\n   or WebSocket-only routes, and\n\n6. optionally, WebSocket PING/PONG messages can be exchanged\n   in an interval to automatically keep the connection alive (e.g. over\n   stateful firewalls) and to better recognize dead connections (e.g. in\n   case of network partitions).\n\nIf you want a more elaborate solution, [NES](https://github.com/hapijs/nes)\nshould be your choice, of course.\n\nLicense\n-------\n\nCopyright (c) 2016-2023 Dr. Ralf S. Engelschall (http://engelschall.com/)\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frse%2Fhapi-plugin-websocket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frse%2Fhapi-plugin-websocket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frse%2Fhapi-plugin-websocket/lists"}