How to Build a Notification System with Angular and Server-Sent Events

A notification feature can be as simple as a bell that shows unread messages, or as important as a live alert for a payment, deployment, support ticket, or security event. Polling an API every few seconds is easy to understand, but it creates unnecessary requests and makes notifications feel late. Server-Sent Events (SSE) provide a lightweight way for a server to push updates to an Angular application over a long-lived HTTP connection.

SSE is especially useful when communication mainly flows from the server to the browser. A user does not need a WebSocket chat session to learn that an invoice has been approved or that a build has failed. With an Angular service, an ASP.NET Core endpoint, and a small amount of state management, you can create a notification system that reconnects automatically, supports unread counts, and remains straightforward to test.

Choosing Server-Sent Events For Notifications

Server-Sent Events use the browser’s built-in EventSource API. The client opens an HTTP connection to an endpoint, and the server keeps that connection open while sending messages in a defined text format. Each event is separated by a blank line, with fields such as event, id, and data.

This model suits notification feeds because the server is the source of new information. A browser can receive a notification when an order changes status, while normal Angular HttpClient requests can still handle actions such as marking an item as read. SSE also reconnects automatically if the connection drops, which is useful for users moving between Wi-Fi and mobile networks.

WebSockets are a better fit when both sides need frequent real-time communication, such as collaborative editing or multiplayer games. SSE has a narrower feature set: it is unidirectional, text-based, and supported by modern browsers. That narrower scope is often an advantage for business applications. It works through ordinary HTTP infrastructure and is usually easier to inspect in browser developer tools.

For an Australian application, consider operational details early. A customer in Perth may connect to infrastructure in Sydney or Melbourne, and an office using the NBN may have a connection that is stable but not perfectly consistent. Notifications should therefore be recoverable from the server rather than treated as the only copy of an important event. A live stream is a delivery mechanism, not your notification database.

Designing The Notification Stream

A useful notification record normally includes an identifier, recipient identifier, message, category, creation time, read state, and optional metadata. Metadata might contain an invoice ID, a route, or an action name. Keep the payload small and avoid putting sensitive information into fields that could be logged by proxies or browser tooling.

A typical JSON message might look like this:

{
  "id": "notification-8421",
  "type": "InvoiceApproved",
  "title": "Invoice approved",
  "message": "Invoice INV-2048 is ready for payment.",
  "createdAt": "2025-02-14T09:30:00Z",
  "link": "/invoices/2048"
}

Persist the notification before publishing it to connected clients. A relational table in SQL Server can hold the durable record, while an in-memory channel or message broker distributes the event to active connections. If the browser disconnects, the Angular application can request recent notifications through a normal API and rebuild the current state.

The id field matters for recovery. EventSource can send a Last-Event-ID header when reconnecting, although the exact behaviour depends on the browser and intermediary. Your endpoint can use that value to replay missed records, or you can combine it with a regular “notifications since timestamp” endpoint. Either approach is safer than assuming every live event reaches the browser.

In larger systems, publishing through Redis, Azure Service Bus, or another broker prevents one web server from knowing only about its own connections. This matters when your Australian customer base is served by several application instances behind a load balancer. A shared event distribution layer keeps a user’s notification stream consistent regardless of which instance accepts the request.

Implementing The Angular Client

Angular should expose notifications through a service rather than allowing components to manage EventSource directly. The service can hold a signal or RxJS observable, open the connection once, and close it when the application no longer needs live updates. The following example uses RxJS and converts browser events into typed notification objects.

import { Injectable, NgZone, OnDestroy } from '@angular/core';
import { Observable, Subject } from 'rxjs';

export interface NotificationItem {
  id: string;
  type: string;
  title: string;
  message: string;
  createdAt: string;
  link?: string;
}

@Injectable({ providedIn: 'root' })
export class NotificationStreamService implements OnDestroy {
  private source?: EventSource;
  private readonly events = new Subject<NotificationItem>();

  readonly notifications$: Observable<NotificationItem> =
    this.events.asObservable();

  constructor(private zone: NgZone) {}

  connect(): void {
    if (this.source) {
      return;
    }

    this.source = new EventSource('/api/notifications/stream', {
      withCredentials: true
    });

    this.source.addEventListener('notification', (event: MessageEvent) => {
      this.zone.run(() => {
        this.events.next(JSON.parse(event.data) as NotificationItem);
      });
    });

    this.source.onerror = () => {
      // EventSource performs automatic reconnects.
      // Add logging or status updates here if required.
    };
  }

  ngOnDestroy(): void {
    this.source?.close();
    this.source = undefined;
    this.events.complete();
  }
}

The NgZone call is useful because native browser events can occur outside Angular’s normal change-detection flow. In newer Angular applications, signals are another good option. A notification store can append incoming events to a signal, increment an unread count, and expose a computed value for the bell component.

Call connect() from an application-level component or an authenticated shell rather than from every page. A notification panel can subscribe to the store and display the latest records. When the user selects an item, send a normal PATCH request to mark it read, then update local state after the server confirms the change.

Native EventSource does not let you add an arbitrary Authorization header. Cookie-based authentication is therefore convenient, provided the endpoint is protected against cross-site request risks and cookies use appropriate Secure and SameSite settings. If your application must use bearer tokens in a header, use an SSE-compatible library or a carefully designed short-lived token in the connection URL. Do not place long-lived access tokens in URLs, where they may appear in logs.

Creating The ASP.NET Core Endpoint

An ASP.NET Core endpoint can write SSE messages using HttpResponse.Body.WriteAsync. A production implementation should use a per-user channel, cancellation tokens, and a repository or broker that supplies new notifications. This simplified controller demonstrates the wire format and the important response headers.

[ApiController]
[Route("api/notifications")]
public sealed class NotificationsController : ControllerBase
{
    [HttpGet("stream")]
    public async Task Stream(CancellationToken cancellationToken)
    {
        Response.StatusCode = StatusCodes.Status200OK;
        Response.ContentType = "text/event-stream";
        Response.Headers.CacheControl = "no-cache";
        Response.Headers.Connection = "keep-alive";

        await Response.Body.FlushAsync(cancellationToken);

        await foreach (var notification in
            notificationHub.ReadForUser(User, cancellationToken))
        {
            var json = JsonSerializer.Serialize(notification);
            await Response.WriteAsync($"id: {notification.Id}\n", cancellationToken);
            await Response.WriteAsync("event: notification\n", cancellationToken);
            await Response.WriteAsync($"data: {json}\n\n", cancellationToken);
            await Response.Body.FlushAsync(cancellationToken);
        }
    }
}

The notificationHub in this example is an application service, not a static global collection. It can maintain an IChannel<NotificationItem> for each active user, remove the channel when the request is cancelled, and publish new records after they are saved. Always filter by the authenticated user on the server. Never trust a user ID supplied by the browser to decide whose messages should be streamed.

Some reverse proxies buffer output until enough bytes have accumulated, which makes a live feed appear broken. Disable response buffering for this route where your hosting platform requires it. Periodic comment frames, such as : keep-alive\n\n, can keep idle connections and proxies active. Set a reasonable limit on concurrent connections, and ensure Kestrel, IIS, Nginx, or a cloud gateway has a timeout suitable for long-lived requests.

Configure cross-origin access only when it is genuinely required. If the Angular site and API use different origins, specify the exact allowed origin and credentials policy rather than enabling every origin. In Australian environments, an application may use a .com.au public site with an API hosted on a separate cloud domain; that arrangement needs deliberate CORS and cookie configuration.

Handling Reliability Security And Testing

A notification system needs a clear failure strategy. EventSource retries after a network failure, but a reconnect does not guarantee that every event sent during the outage will be replayed. On connection, load the latest notifications from the API. When a live event arrives, merge it by ID so that a replayed item does not appear twice.

The browser should also show connection state when it affects the user experience. A small “Live updates paused” indicator is preferable to silently losing alerts. Do not make every notification sound urgent. Separate categories such as billing, account security, workflow updates, and marketing messages, and let users control non-essential categories. This is particularly important when handling personal information under the Australian Privacy Act and the Australian Privacy Principles.

Security includes authorisation, output encoding, rate limits, and payload validation. Store plain notification text or safely rendered content rather than accepting arbitrary HTML from another user. If a notification links to a record, verify access again when the link is opened. A notification arriving successfully does not grant permission to view the referenced resource.

Testing can happen at several levels. Unit-test the Angular store by sending synthetic notification events and checking unread counts, ordering, duplicate handling, and cleanup. Integration-test the endpoint with an authenticated test user, confirm the text/event-stream content type, and verify that a second user cannot receive the first user’s events. Test cancellation when a browser tab closes, as abandoned streams can otherwise consume server resources.

Finally, test the deployment path rather than stopping at localhost. Check reconnect behaviour during an app restart, proxy buffering, multiple application instances, expired cookies, daylight-saving changes between AEST and AEDT, and slow connections. A notification created in a Brisbane office should have a consistent UTC timestamp and be rendered in the user’s local time. Use structured logs for connection opened, connection closed, event published, and replay failed, while excluding message contents that could expose private data.

A practical first release can use SQL Server for durable records, an in-process channel for a single server, Angular signals or RxJS for the client store, and one SSE endpoint. Once traffic grows, move distribution to a shared broker without changing the browser contract. This keeps the initial implementation focused while leaving room for a platform serving users across Sydney, Adelaide, Darwin, and regional areas.

Build the durable notification API first, then add the SSE stream as a fast delivery path. Create a small Angular notification store, protect the connection with the same care as any other authenticated endpoint, and test it through the proxy and hosting environment you actually deploy. With those foundations in place, live alerts can feel immediate without turning the application into an unnecessarily complex real-time system.