{"id":20514241,"url":"https://github.com/webreflection/bidi-sse","last_synced_at":"2025-04-14T00:12:10.667Z","repository":{"id":65993108,"uuid":"432152219","full_name":"WebReflection/bidi-sse","owner":"WebReflection","description":"Bidirectional Server-sent Events","archived":false,"fork":false,"pushed_at":"2021-12-02T12:35:32.000Z","size":114,"stargazers_count":41,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-14T00:11:59.551Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"isc","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/WebReflection.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,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2021-11-26T11:19:21.000Z","updated_at":"2025-02-11T15:51:27.000Z","dependencies_parsed_at":"2023-05-21T16:45:15.646Z","dependency_job_id":null,"html_url":"https://github.com/WebReflection/bidi-sse","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebReflection%2Fbidi-sse","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebReflection%2Fbidi-sse/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebReflection%2Fbidi-sse/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/WebReflection%2Fbidi-sse/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/WebReflection","download_url":"https://codeload.github.com/WebReflection/bidi-sse/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248799954,"owners_count":21163404,"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-15T21:15:29.023Z","updated_at":"2025-04-14T00:12:10.642Z","avatar_url":"https://github.com/WebReflection.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# bidi-sse\n\n![two ways](./test/bidi-sse.jpg)\n\n\u003csup\u003e**Social Media Photo by [Ian Taylor](https://unsplash.com/@carrier_lost) on [Unsplash](https://unsplash.com/)**\u003c/sup\u003e\n\nBidirectional [Server-sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events).\n\n\n### About\n\nHeavily inspired by the awesome [ws module](https://github.com/websockets/ws#readme), *bidi-sse* provides a *Web Sockets* friendly API, although based on both [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) primitives.\n\nThanks to its different approach, both client side and server side code are minimal (~0.7K on the client, few lines on the server), and there is no need to roundtrip *ping* / *pong* to know whenever a client is gone, as that happens pretty much instantly, or better, as soon as the alive connection gets closed.\n\n\n### Example\n\nFollowing a very simple setup to explain the basics behind this module, one for the *client side*, and one for the *server side*.\n\n\n\u003cdetails open\u003e\n  \u003csummary\u003e\u003cstrong\u003eClient\u003c/strong\u003e\u003c/summary\u003e\n  \u003cdiv\u003e\n\n```js\nimport BidiSSE from 'bidi-sse/client';\n// or import BidiSSE from 'https://unpkg.com/bidi-sse';\n\nconst bidi = new BidiSSE('/bidi-path');\n\n// use it like a socket\nbidi.on('open', () =\u003e {\n  console.log('open');\n  // it can send data once connected\n  bidi.send({some: 'data'});\n});\n\nbidi.on('message', console.log);\nbidi.on('error', console.error);\nbidi.on('close', () =\u003e console.log('closed'));\n```\n  \u003c/div\u003e\n\u003c/details\u003e\n\n\u003cdetails open\u003e\n  \u003csummary\u003e\u003cstrong\u003eServer\u003c/strong\u003e\u003c/summary\u003e\n  \u003cdiv\u003e\n\n```js\nconst express = require('express');\nconst BidiSSE = require('bidi-sse/server');\n// or import BidiSSE from 'https://unpkg.com/bidi-sse/esm/server.js';\n\nconst bidi = new BidiSSE('/bidi-path');\n\n// use it as handler or check bidi.handler(req, res) directly\nconst app = express();\napp.use(bidi.handler);\napp.use(express.static(__dirname));\napp.listen(8080);\n\n// and set it up like a socket\nbidi.on('connection', client =\u003e {\n\n  // all clients via .clients for broadcast\n  console.log('clients', bidi.clients.size);\n\n  // setup clients also like sockets\n  client.on('message', data =\u003e {\n    console.log('client', data);\n    client.send(data);\n  });\n\n  client.on('close', () =\u003e {\n    console.log('client is gone');\n  });\n});\n```\n  \u003c/div\u003e\n\u003c/details\u003e\n\n\n\n## API\n\nBoth *client* and *server* constructors accept a `path` to enable as *bidi-sse*, and an optional `options` object.\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cstrong\u003eClient\u003c/strong\u003e - a simplified emitter\u003c/summary\u003e\n  \u003cdiv\u003e\n\n```js\nconst bidi = new BidiSSE('/some-path', {\n  // optional fetch options to merge per each send\n  // using credentials 'omit' set withCredentials\n  // for EventSource as `false`: it's `true` by default.\n  fetch: {credentials: 'omit'},\n\n  // default JSON serializer to send/receive data\n  JSON\n});\n\n// readyState is one of the static BidiSSE values:\nbidi.readyState;\n// BidiSSE.CONNECTING ➡ open event not fired yet: cannot send\n// BidiSSE.OPEN       ➡ open fired: can now send\n// BidiSSE.CLOSING    ➡ connection error occurred\n// BidiSSE.CLOSED     ➡ bidi.close(); or after connection error\n\n// events + chainable .on(type, fn) method\nbidi.once('open', () =\u003e console.info('open'));\nbidi.on('message', console.log);\nbidi.on('error', console.error);\nbidi.once('close', () =\u003e console.info('close'));\n\n// methods: send throws if readyState is not OPEN\nbidi.send({any: 'data'});\nbidi.close();\n\n// extra\nbidi.emit('type', ...[{any: 'data'}]);\n```\n  \u003c/div\u003e\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cstrong\u003eServer\u003c/strong\u003e - an event emitter with \u003cem\u003eclients\u003c/em\u003e notified via \u003ccode\u003econnection\u003c/code\u003e\u003c/summary\u003e\n  \u003cdiv\u003e\n\n```js\nconst bidi = new BidiSSE('/some-path', {\n  // if its value is `\"cors\"` it enables CORS via headers\n  mode: '',\n\n  // optional headers to include per each SSE initialization\n  // or further posted data via send(...)\n  headers: {},\n\n  // default JSON serializer to send/receive data\n  JSON\n});\n\n// a read only *Set* of clients, where each client has\n// the same properties and methods of the client side one\nbidi.clients;\n\n// an auto-bound method usable as express handler or within\n// basic nodejs createServer logic. Returns true if the request\n// was handled as Server-sent Event\nbidi.handler;\n\n// events + chainable .on(type, fn) method\nbidi.on('connection', client =\u003e {\n  // client is unique per visitor and it has all features\n  // a client-side bidi instance has\n});\nbidi.on('close', () =\u003e { console.log('all gone'); });\n\n// methods: close throw away all connected clients, then resolves\nbidi.close();\n```\n  \u003c/div\u003e\n\u003c/details\u003e\n\n\n## Use cases\n\nIt is very important to understand *where* this module can easily *fail*, as opposite of being a solution ...\n\n  * this module assumes *every request passes through the same stack*, meaning that *cluster*, *serverless*, *load balance*, or any stack that might diverge the request somewhere else, will easily fail if the browser client `EventSource` points at a different end of the spectrum, and further *UUIDs related* request are sent elsewhere\n\n  * this module was mostly born to satisfy [proxied-node](https://github.com/WebReflection/proxied-node#readme) constrains and architecrture, among IoT caveats, so *don't use this in production unless you really [understand how this module works](https://github.com/WebReflection/bidi-sse#how-it-works) 👍*\n\n\n### How it works\n\n  * an *EventSource* client request is intercepted and handled on the server:\n    * the response object is trapped until the client disconnects\n    * a server side *client* is created and the long living response object is associated with it\n    * the very first server-sent event is a unique identifier\n    * the server side *client* is associated to this unique identifier and a *connection* event emitted, passing such *client* as ready to communicate\n  * the client stores internally such unique identifier and emit it's *open* listener, enabling its communication ability\n  * each time the client instance `.send(data)` is invoked, the same *EventSource's href* plus the unique identifier is used to *POST* the data as serialized format\n  * the server intercepts *POST* requests and handle these internally if:\n    * the url is *the same as the initial one defined to trap responses*\n    * there is *a known UUID* associated with the url as `bidi-sse` query string\n  * the sent data is built as string via all its chunks, and then deserialized through the same `stringify` and `parse` mechanism used on the client. This is *JSON* by default, but [it could be any different library](https://github.com/WebReflection/bidi-sse#using-different-serialization)\n    * if the `parse(postedData)` operation fails, an *error* is triggered on the client side, but only if it's still connected\n    * if the operation is successful, a *message* event with the parsed data is invoked on the server \"*client's counterpart*\"\n  * when the server side *client* `.send(data)` is invoked, a *message* event is emitted in the browser's *client* side, and through the same `stringify` and `parse` procedure\n\n\n#### Using different serialization\n\nPlease note that the **JSON** reference library to *stringify* and *parse* must be the same for both *client* and *server*.\n\n[flatted](https://www.npmjs.com/package/flatted) and [@ungap/structured-clone/json](https://github.com/ungap/structured-clone#tojson) are just two of the many possible parser alternatives, able to deal with recursion and, in the structured clone case, with also more data types and primitives.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebreflection%2Fbidi-sse","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwebreflection%2Fbidi-sse","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebreflection%2Fbidi-sse/lists"}