Angular Server-Sent Events Client
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.
Common errors
-
Error: NG0201: No provider for SseClient!
cause The `SseClient` service has not been provided in your Angular application's module or component hierarchy.fixAdd `SseClient` to the `providers` array in your `AppModule` (or a feature module where it's used) to make it injectable: `providers: [SseClient]`. -
Expected 1-2 arguments, but got 4.
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).fixEnsure 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`. -
Property 'type' does not exist on type 'unknown'.
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`.fixUse 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; /* ... */ }`.
Warnings
- breaking 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.
- gotcha 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.
- gotcha 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.
- gotcha 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.
Install
-
npm install ngx-sse-client -
yarn add ngx-sse-client -
pnpm add ngx-sse-client
Imports
- SseClient
const SseClient = require('ngx-sse-client');import { SseClient } from 'ngx-sse-client'; - SseOption
import { SseOption } from 'ngx-sse-client'; - HttpHeaders
import { HttpHeaders } from 'ngx-sse-client';import { HttpHeaders } from '@angular/common/http';
Quickstart
import { Component, OnInit } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import { SseClient } from 'ngx-sse-client';
@Component({
selector: 'app-root',
template: `<h1>SSE Stream Example</h1><p>Check console for events.</p>`,
})
export class AppComponent implements OnInit {
constructor(private sseClient: SseClient) {}
ngOnInit(): void {
const headers = new HttpHeaders().set('Authorization', `Basic YWRtaW46YWRtaW4=`);
// Example of subscribing to an SSE stream with custom options and POST method
this.sseClient.stream(
'/api/subscribe', // Replace with your SSE endpoint
{ keepAlive: true, reconnectionDelay: 1_000, responseType: 'event' },
{ headers },
'POST'
).subscribe({
next: (event) => {
if (event.type === 'error') {
const errorEvent = event as ErrorEvent;
console.error('SSE Error Event:', errorEvent.error, errorEvent.message);
} else {
const messageEvent = event as MessageEvent;
console.info(`SSE Message (${messageEvent.type}):`, messageEvent.data);
}
},
error: (err) => {
console.error('SSE Subscription Error:', err);
},
complete: () => {
console.log('SSE Stream Completed.');
}
});
}
}