{"id":15024973,"url":"https://github.com/binaryminds/react-native-sse","last_synced_at":"2025-05-16T13:02:03.050Z","repository":{"id":42484938,"uuid":"360887136","full_name":"binaryminds/react-native-sse","owner":"binaryminds","description":"Event Source implementation for React Native. Server-Sent Events (SSE) for iOS and Android 🚀","archived":false,"fork":false,"pushed_at":"2024-08-05T20:57:54.000Z","size":20,"stargazers_count":273,"open_issues_count":22,"forks_count":39,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-05-12T08:06:18.993Z","etag":null,"topics":["android","event-source","eventsource","ios","react-native","sse","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/react-native-sse","language":"JavaScript","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/binaryminds.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,"publiccode":null,"codemeta":null}},"created_at":"2021-04-23T13:06:35.000Z","updated_at":"2025-05-12T07:09:54.000Z","dependencies_parsed_at":"2024-06-18T15:35:49.014Z","dependency_job_id":"f5e854f3-1595-44f8-82ef-7346769dac2f","html_url":"https://github.com/binaryminds/react-native-sse","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binaryminds%2Freact-native-sse","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binaryminds%2Freact-native-sse/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binaryminds%2Freact-native-sse/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binaryminds%2Freact-native-sse/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/binaryminds","download_url":"https://codeload.github.com/binaryminds/react-native-sse/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254535787,"owners_count":22087394,"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":["android","event-source","eventsource","ios","react-native","sse","typescript"],"created_at":"2024-09-24T20:01:17.995Z","updated_at":"2025-05-16T13:02:03.027Z","avatar_url":"https://github.com/binaryminds.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# React Native EventSource (Server-Sent Events) 🚀\n\nYour missing EventSource implementation for React Native! React-Native-SSE library supports TypeScript.\n\n## 💿 Installation\n\nWe use XMLHttpRequest to establish and handle an SSE connection, so you don't need an additional native Android and iOS implementation. It's easy, just install it with your favorite package manager:\n\n### Yarn\n\n```bash\nyarn add react-native-sse\n```\n\n### NPM\n\n```bash\nnpm install --save react-native-sse\n```\n\n## 🎉 Usage\n\nWe are using Server-Sent Events as a convenient way of establishing and handling Mercure connections. It helps us keep data always up-to-date, synchronize data between devices, and improve real-time workflow. Here you have some usage examples:\n\n### Import\n\n```js\nimport EventSource from \"react-native-sse\";\n```\n\n### Connection and listeners\n\n```js\nimport EventSource from \"react-native-sse\";\n\nconst es = new EventSource(\"https://your-sse-server.com/.well-known/mercure\");\n\nes.addEventListener(\"open\", (event) =\u003e {\n  console.log(\"Open SSE connection.\");\n});\n\nes.addEventListener(\"message\", (event) =\u003e {\n  console.log(\"New message event:\", event.data);\n});\n\nes.addEventListener(\"error\", (event) =\u003e {\n  if (event.type === \"error\") {\n    console.error(\"Connection error:\", event.message);\n  } else if (event.type === \"exception\") {\n    console.error(\"Error:\", event.message, event.error);\n  }\n});\n\nes.addEventListener(\"close\", (event) =\u003e {\n  console.log(\"Close SSE connection.\");\n});\n```\n\nIf you want to use Bearer token and/or topics, look at this example (TypeScript):\n\n```typescript\nimport React, { useEffect, useState } from \"react\";\nimport { View, Text } from \"react-native\";\nimport EventSource, { EventSourceListener } from \"react-native-sse\";\nimport \"react-native-url-polyfill/auto\"; // Use URL polyfill in React Native\n\ninterface Book {\n  id: number;\n  title: string;\n  isbn: string;\n}\n\nconst token = \"[my-hub-token]\";\n\nconst BookList: React.FC = () =\u003e {\n  const [books, setBooks] = useState\u003cBook[]\u003e([]);\n\n  useEffect(() =\u003e {\n    const url = new URL(\"https://your-sse-server.com/.well-known/mercure\");\n    url.searchParams.append(\"topic\", \"/book/{bookId}\");\n\n    const es = new EventSource(url, {\n      headers: {\n        Authorization: {\n          toString: function () {\n            return \"Bearer \" + token;\n          },\n        },\n      },\n    });\n\n    const listener: EventSourceListener = (event) =\u003e {\n      if (event.type === \"open\") {\n        console.log(\"Open SSE connection.\");\n      } else if (event.type === \"message\") {\n        const book = JSON.parse(event.data) as Book;\n\n        setBooks((prevBooks) =\u003e [...prevBooks, book]);\n\n        console.log(`Received book ${book.title}, ISBN: ${book.isbn}`);\n      } else if (event.type === \"error\") {\n        console.error(\"Connection error:\", event.message);\n      } else if (event.type === \"exception\") {\n        console.error(\"Error:\", event.message, event.error);\n      }\n    };\n\n    es.addEventListener(\"open\", listener);\n    es.addEventListener(\"message\", listener);\n    es.addEventListener(\"error\", listener);\n\n    return () =\u003e {\n      es.removeAllEventListeners();\n      es.close();\n    };\n  }, []);\n\n  return (\n    \u003cView\u003e\n      {books.map((book) =\u003e (\n        \u003cView key={`book-${book.id}`}\u003e\n          \u003cText\u003e{book.title}\u003c/Text\u003e\n          \u003cText\u003eISBN: {book.isbn}\u003c/Text\u003e\n        \u003c/View\u003e\n      ))}\n    \u003c/View\u003e\n  );\n};\n\nexport default BookList;\n```\n\n### Usage with React Redux\n\nSince the listener is a closure it has access only to the component values from the first render. Each subsequent render\nhas no effect on already defined listeners.\n\nIf you use Redux you can get the actual value directly from the store instance.\n\n```typescript\n// full example: https://snack.expo.dev/@quiknull/react-native-sse-redux-example\ntype CustomEvents = \"ping\";\n\nconst Example: React.FC = () =\u003e {\n    const name = useSelector((state: RootState) =\u003e state.user.name);\n\n    const pingHandler: EventSourceListener\u003cCustomEvents, 'ping'\u003e = useCallback(\n        (event) =\u003e {\n            // In Event Source Listeners in connection with redux\n            // you should read state directly from store object.\n            console.log(\"User name from component selector: \", name); // bad\n            console.log(\"User name directly from store: \", store.getState().user.name); // good\n        },\n        []\n    );\n\n    useEffect(() =\u003e {\n        const token = \"myToken\";\n        const url = new URL(\"https://demo.mercure.rocks/.well-known/mercure\");\n        url.searchParams.append(\n            \"topic\",\n            \"https://example.com/my-private-topic\"\n        );\n\n        const es = new EventSource\u003cCustomEvents\u003e(url, {\n            headers: {\n                Authorization: {\n                    toString: function () {\n                        return \"Bearer \" + token;\n                    }\n                }\n            }\n        });\n\n        es.addEventListener(\"ping\", pingHandler);\n    }, []);\n};\n```\n\n## 📖 Configuration\n\n```typescript\nnew EventSource(url: string | URL, options?: EventSourceOptions);\n```\n\n### Options\n\n```typescript\nconst options: EventSourceOptions = {\n  method: 'GET', // Request method. Default: GET\n  timeout: 0, // Time (ms) after which the connection will expire without any activity. Default: 0 (no timeout)\n  timeoutBeforeConnection: 500, // Time (ms) to wait before initial connection is made. Default: 500\n  withCredentials: false, // Include credentials in cross-site Access-Control requests. Default: false\n  headers: {}, // Your request headers. Default: {}\n  body: undefined, // Your request body sent on connection. Default: undefined\n  debug: false, // Show console.debug messages for debugging purpose. Default: false\n  pollingInterval: 5000, // Time (ms) between reconnections. If set to 0, reconnections will be disabled. Default: 5000\n  lineEndingCharacter: null // Character(s) used to represent line endings in received data. Common values: '\\n' for LF (Unix/Linux), '\\r\\n' for CRLF (Windows), '\\r' for CR (older Mac). Default: null (Automatically detect from event)\n}\n```\n\n## 🚀 Advanced usage with TypeScript\n\nUsing EventSource you can handle custom events invoked by the server:\n\n```typescript\nimport EventSource, { EventSourceListener, EventSourceEvent } from \"react-native-sse\";\n\ntype MyCustomEvents = \"ping\" | \"clientConnected\" | \"clientDisconnected\";\n\nconst es = new EventSource\u003cMyCustomEvents\u003e(\n  \"https://your-sse-server.com/.well-known/hub\"\n);\n\nes.addEventListener(\"open\", (event) =\u003e {\n  console.log(\"Open SSE connection.\");\n});\n\nes.addEventListener(\"ping\", (event) =\u003e {\n  console.log(\"Received ping with data:\", event.data);\n});\n\nes.addEventListener(\"clientConnected\", (event) =\u003e {\n  console.log(\"Client connected:\", event.data);\n});\n\nes.addEventListener(\"clientDisconnected\", (event) =\u003e {\n  console.log(\"Client disconnected:\", event.data);\n});\n```\n\nUsing one listener for all events:\n\n```typescript\nimport EventSource, { EventSourceListener } from \"react-native-sse\";\n\ntype MyCustomEvents = \"ping\" | \"clientConnected\" | \"clientDisconnected\";\n\nconst es = new EventSource\u003cMyCustomEvents\u003e(\n  \"https://your-sse-server.com/.well-known/hub\"\n);\n\nconst listener: EventSourceListener\u003cMyCustomEvents\u003e = (event) =\u003e {\n  if (event.type === 'open') {\n    // connection opened\n  } else if (event.type === 'message') {\n    // ...\n  } else if (event.type === 'ping') {\n    // ...\n  }\n}\nes.addEventListener('open', listener);\nes.addEventListener('message', listener);\nes.addEventListener('ping', listener);\n```\n\nUsing generic type for one event:\n\n```typescript\nimport EventSource, { EventSourceListener, EventSourceEvent } from \"react-native-sse\";\n\ntype MyCustomEvents = \"ping\" | \"clientConnected\" | \"clientDisconnected\";\n\nconst es = new EventSource\u003cMyCustomEvents\u003e(\n  \"https://your-sse-server.com/.well-known/hub\"\n);\n\nconst pingListener: EventSourceListener\u003cMyCustomEvents, 'ping'\u003e = (event) =\u003e {\n  // ...\n}\n// or\nconst pingListener = (event: EventSourceEvent\u003c'ping', MyCustomEvents\u003e) =\u003e {\n  // ...\n}\n\nes.addEventListener('ping', pingListener);\n```\n\n`MyCustomEvents` in `EventSourceEvent` is optional, but it's recommended to use it in order to have better type checking.\n\n## 🚀 Usage with ChatGPT\n\nIf you want to use ChatGPT with React Native, you can use the following example:\n\n```typescript\nimport { useEffect, useState } from \"react\";\nimport { Text, View } from \"react-native\";\nimport EventSource from \"react-native-sse\";\n\nconst OpenAIToken = '[Your OpenAI token]';\n\nexport default function App() {\n  const [text, setText] = useState\u003cstring\u003e(\"Loading...\");\n\n  useEffect(() =\u003e {\n    const es = new EventSource(\n      \"https://api.openai.com/v1/chat/completions\",\n      {\n        headers: {\n          \"Content-Type\": \"application/json\",\n          Authorization: `Bearer ${OpenAIToken}`,\n        },\n        method: \"POST\",\n        // Remember to read the OpenAI API documentation to set the correct body\n        body: JSON.stringify({\n          model: \"gpt-3.5-turbo-0125\",\n          messages: [\n            {\n              role: \"system\",\n              content: \"You are a helpful assistant.\",\n            },\n            {\n              role: \"user\",\n              content: \"What is the meaning of life?\",\n            },\n          ],\n          max_tokens: 600,\n          n: 1,\n          temperature: 0.7,\n          stream: true,\n        }),\n        pollingInterval: 0, // Remember to set pollingInterval to 0 to disable reconnections\n      }\n    );\n\n    es.addEventListener(\"open\", () =\u003e {\n      setText(\"\");\n    });\n\n    es.addEventListener(\"message\", (event) =\u003e {\n      if (event.data !== \"[DONE]\") {\n        const data = JSON.parse(event.data);\n\n        if (data.choices[0].delta.content !== undefined) {\n          setText((text) =\u003e text + data.choices[0].delta.content);\n        }\n      }\n    });\n\n    return () =\u003e {\n      es.removeAllEventListeners();\n      es.close();\n    };\n  }, []);\n\n  return (\n    \u003cView\u003e\n      \u003cText\u003e{text}\u003c/Text\u003e\n    \u003c/View\u003e\n  );\n}\n```\n\n\n---\n\nCustom events always emit result with following interface:\n\n```typescript\nexport interface CustomEvent\u003cE extends string\u003e {\n  type: E;\n  data: string | null;\n  lastEventId: string | null;\n  url: string;\n}\n```\n\n## 👏 Contribution\n\nIf you see our library is not working properly, feel free to open an issue or create a pull request with your fixes.\n\n## 📄 License\n\n```\nThe MIT License\n\nCopyright (c) 2021 Binary Minds\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinaryminds%2Freact-native-sse","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbinaryminds%2Freact-native-sse","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinaryminds%2Freact-native-sse/lists"}