Server Sent Events in Angular + Node

Chris Bautista
Jan 1, 2019 · 2 min read

In this article we’ll go over how to implement Server-sent events (SSE)using Node and Angular.

Here is an excerpt from MDN that briefly describes Server-sent events.

Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it’s possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page.

Now how can we create a server-sent event in Angular? A common approach would just be to have a service responsible for creating them. Here’s a basic example below.

The service above will just simply create an EventSource that will receive events from the server. Let’s take it a step further and see how we can leverage this util method.

The service will return an observable that will emit data coming from the EventSource. You’ll notice we are also incorporating zone.js. We need NgZone to alert Angular when an event occurs because it happens outside of the framework.

Here’s an example of how you can call it in a component.

Okay that covers the Angular portion.. lets see how we can implement SSE in node.

The above example is how I mocked out SSE locally to test. What is happening here is that a message is pushed to the client every 10 seconds.

Hopefully this has been helpful!

Chris Bautista

Written by

Senior Frontend Developer @ GOAT. Love sharing what I know and learning from others.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade