DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at on


Server-Sent Events 101

Server-Sent Events (SSE) is a unidirectional communication between the client and server. The client initiates the connection with the server using EventSource API.

The previously mentioned API can also listen to the events from the server, listen for errors, and close the connection.

const eventSource = new EventSource(url);

eventSource.onmessage = ({ data }) => {
  const eventData = JSON.parse(data);
  // handling the data from the server

eventSource.onerror = () => {
  // error handling

Enter fullscreen mode Exit fullscreen mode

A server can send the events in text/event-stream format to the client once the client establishes the client-server connection. A server can filter clients by query parameter and send them only the appropriate events.

In the following example, the NestJS server sends the events only to a specific client distinguished by its e-mail address.

import { Controller, Query, Sse } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';
import { MessageEvent, MessageEventData } from './message-event.interface';
import { SseQueryDto } from './sse-query.dto';

export class AppController {
  constructor(private readonly eventService: EventEmitter2) {}

  sse(@Query() sseQuery: SseQueryDto): Observable<MessageEvent> {
    const subject$ = new Subject();

    this.eventService.on(FILTER_VERIFIED, data => {
      if ( !== return;

      subject$.next({ isVerifiedFilter: data.isVerified });

    return subject$.pipe(
      map((data: MessageEventData): MessageEvent => ({ data })),
  // ...
Enter fullscreen mode Exit fullscreen mode

Emitting the event mentioned above is done in the following way.

const filterVerifiedEvent = new FilterVerifiedEvent(); =;
filterVerifiedEvent.isVerified = true;
this.eventService.emit(FILTER_VERIFIED, filterVerifiedEvent);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)