{"id":16864,"library":"ngx-sse-client","title":"Angular Server-Sent Events Client","description":"ngx-sse-client is an Angular library providing a robust client for Server-Sent Events (SSE), designed as an alternative to the native `EventSource` API. Currently at stable version 21.0.0, this package typically releases new major versions in alignment with Angular's own major releases, ensuring compatibility with the latest Angular ecosystem. Its key differentiator lies in leveraging Angular's `HttpClient` for SSE stream requests, which enables seamless integration with `HttpInterceptor` for authentication, logging, and error handling. It also supports flexible HTTP methods (e.g., POST instead of just GET) and exposes event streams as RxJS Observables, aligning with Angular's reactive programming paradigm. This allows for more advanced control and error management compared to traditional `EventSource` implementations, which lack interceptor support and direct Observable integration.","status":"active","version":"21.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/marcospds/ngx-sse-client","tags":["javascript","angular","sse","sse-client","ngx","typescript"],"install":[{"cmd":"npm install ngx-sse-client","lang":"bash","label":"npm"},{"cmd":"yarn add ngx-sse-client","lang":"bash","label":"yarn"},{"cmd":"pnpm add ngx-sse-client","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for Angular-specific features like HttpClient and DI.","package":"@angular/common","optional":false},{"reason":"Peer dependency for Angular core functionalities, including dependency injection and component lifecycle.","package":"@angular/core","optional":false}],"imports":[{"note":"This is an Angular service, primarily used with ES Modules and TypeScript. CommonJS `require` is not supported for Angular libraries.","wrong":"const SseClient = require('ngx-sse-client');","symbol":"SseClient","correct":"import { SseClient } from 'ngx-sse-client';"},{"note":"Interface for configuring the SSE stream. Not directly injected but used for type declarations.","symbol":"SseOption","correct":"import { SseOption } from 'ngx-sse-client';"},{"note":"HttpHeaders is part of Angular's HttpClient module, not `ngx-sse-client` itself. It is commonly used when making SSE requests with custom headers.","wrong":"import { HttpHeaders } from 'ngx-sse-client';","symbol":"HttpHeaders","correct":"import { HttpHeaders } from '@angular/common/http';"}],"quickstart":{"code":"import { Component, OnInit } from '@angular/core';\nimport { HttpHeaders } from '@angular/common/http';\nimport { SseClient } from 'ngx-sse-client';\n\n@Component({\n  selector: 'app-root',\n  template: `<h1>SSE Stream Example</h1><p>Check console for events.</p>`,\n})\nexport class AppComponent implements OnInit {\n  constructor(private sseClient: SseClient) {}\n\n  ngOnInit(): void {\n    const headers = new HttpHeaders().set('Authorization', `Basic YWRtaW46YWRtaW4=`);\n\n    // Example of subscribing to an SSE stream with custom options and POST method\n    this.sseClient.stream(\n      '/api/subscribe', // Replace with your SSE endpoint\n      { keepAlive: true, reconnectionDelay: 1_000, responseType: 'event' },\n      { headers },\n      'POST'\n    ).subscribe({\n      next: (event) => {\n        if (event.type === 'error') {\n          const errorEvent = event as ErrorEvent;\n          console.error('SSE Error Event:', errorEvent.error, errorEvent.message);\n        } else {\n          const messageEvent = event as MessageEvent;\n          console.info(`SSE Message (${messageEvent.type}):`, messageEvent.data);\n        }\n      },\n      error: (err) => {\n        console.error('SSE Subscription Error:', err);\n      },\n      complete: () => {\n        console.log('SSE Stream Completed.');\n      }\n    });\n  }\n}","lang":"typescript","description":"Demonstrates injecting the `SseClient` service, subscribing to an SSE stream with custom options (keep-alive, reconnection delay, event response type), including HTTP headers for authorization, and using a POST method. It also shows handling both `MessageEvent` and `ErrorEvent` responses within the subscription."},"warnings":[{"fix":"Always check the `peerDependencies` in `package.json` or the changelog for `ngx-sse-client` to ensure compatibility with your Angular version before upgrading. Upgrade `ngx-sse-client` to the major version that matches your Angular version.","message":"Major versions of `ngx-sse-client` are tightly coupled with specific Angular versions. Upgrading Angular often requires a corresponding `ngx-sse-client` major version upgrade, which can introduce breaking changes. For example, v21.0.0 requires Angular >=21.0.0.","severity":"breaking","affected_versions":">=17.0.0"},{"fix":"For comprehensive error handling, especially during development or for robust applications, use `responseType: 'event'`. This allows you to differentiate between `MessageEvent` and `ErrorEvent` and react to stream errors. Only use `responseType: 'text'` if you are certain your server will not send error events or if you prefer to handle all stream interruptions as completion events.","message":"When `responseType` is set to `'text'`, the library will only return the message data. No errors will be propagated through the Observable's error channel or returned as `ErrorEvent` types within the stream, effectively suppressing error handling.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure you call `.unsubscribe()` on the `Subscription` object obtained from `sseClient.stream().subscribe()` when the component or service using it is destroyed or no longer needs the stream. For Angular components, this typically means implementing `ngOnDestroy`.","message":"If `keepAlive` is set to `true`, the SSE connection will automatically attempt to reconnect if it's closed (e.g., by timeout or completion). To explicitly terminate the stream, you *must* `unsubscribe` from the Observable. Failure to do so will result in continuous reconnection attempts, potentially consuming resources.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Configure your proxy server (e.g., Nginx) to disable buffering for SSE endpoints. Common Nginx configurations include `proxy_buffering off;` and `proxy_set_header Connection '';` for the SSE location. Also, ensure your application server sends `X-Accel-Buffering: no` header.","message":"SSE connections can be buffered by intermediate proxies or web servers like Nginx, leading to delayed delivery of events. This can negate the real-time benefits of SSE.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Add `SseClient` to the `providers` array in your `AppModule` (or a feature module where it's used) to make it injectable: `providers: [SseClient]`.","cause":"The `SseClient` service has not been provided in your Angular application's module or component hierarchy.","error":"Error: NG0201: No provider for SseClient!"},{"fix":"Ensure your `ngx-sse-client` version is up-to-date (currently v21.0.0 for Angular 21) and that your `stream` method call matches the signature of the installed version. You may need to update the library: `npm install ngx-sse-client@latest`.","cause":"This error can occur if you are using an older version of `ngx-sse-client` where the `stream` method had fewer parameters, but your code is written for a newer version that accepts more arguments (e.g., HTTP method and request options).","error":"Expected 1-2 arguments, but got 4."},{"fix":"Use type guards or type assertions within your subscription callback to correctly infer the type of the event. For example: `if (event.type === 'error') { const errorEvent = event as ErrorEvent; /* ... */ } else { const messageEvent = event as MessageEvent; /* ... */ }`.","cause":"When `responseType` is `'event'`, the `subscribe` callback receives an `Event` object, which needs to be type-asserted to `MessageEvent` or `ErrorEvent` to access specific properties like `data` or `message`.","error":"Property 'type' does not exist on type 'unknown'."}],"ecosystem":"npm","meta_description":null}