DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev 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
};

eventSource.close();
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';

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

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

    this.eventService.on(FILTER_VERIFIED, data => {
      if (sseQuery.email !== data.email) 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.email = user.email;
filterVerifiedEvent.isVerified = true;
this.eventService.emit(FILTER_VERIFIED, filterVerifiedEvent);
Enter fullscreen mode Exit fullscreen mode

Course

Build your SaaS in 2 weeks - Start Now

Top comments (3)

Collapse
 
der_gopher profile image
Alex Pliutau

Great write up! Does anyone use Server-Sent Events in their projects? If yes, for which use cases? This video dives into the main building blocks of Server-Sent Events in Go.
youtu.be/nvijc5J-JAQ

Collapse
 
eliseonop profile image
Eliseo Falcon • Edited

what is the structure of you MessageData?
import { MessageEvent, MessageEventData } from './message-event.interface';
pdta: pass code pls

Collapse
 
zsevic profile image
Željko Šević • Edited

for this example, it's:

export interface MessageEventData {
  email: string;
  isVerified: boolean;
}

export interface MessageEvent {
  data: MessageEventData;
}
Enter fullscreen mode Exit fullscreen mode