Frontend Implementation

Hi everyone! Building on our previous article on NestJS SSE, we are now moving forward to discuss how a VueJS application can consume those Server-Sent Events (SSE) that were emitted by a NestJS backend. This ensures an effective Event Driven Architecture (EDA), keeping your frontend seamlessly in sync with the backend.

Dealing with backend events can be fairly straightforward, especially when compared to the challenge of updating the frontend in real-time. This is where SSE becomes a lifesaver, providing an efficient mechanism to keep the frontend updated alongside backend events.

This article does not aim to compare this solution with others but rather focuses on sharing a hands-on implementation that has proven to be both functional and adaptable.

For those new to SSE or in need of a refresher, reviewing the official NestJS documentation and the Github example can be helpful. Once you're familiar with the basics, let's explore how to integrate SSEs into a VueJS app.

Consuming SSE in VueJS

Start by creating an instance of EventSource in your VueJS application. This instance should connect to the SSE endpoint set up in your NestJS backend. Here's an example within a Vue component:

<script>
export default {
data() {
return {
eventSource: null,
messages: []
}
},
created() {
this.eventSource = new EventSource('http://localhost:8002/sse');
this.eventSource.onmessage = (event) => {
this.messages.push('New message: ' + event.data);
};
},
beforeDestroy() {
this.eventSource.close();
},
}
</script>

The code above sets up an instance of EventSource when the Vue component is created and listens for incoming SSE messages. Each time a message is received, it's added to the messages array; This connection is then closed when the Vue component is destroyed to prevent memory leaks.

You can then utilize the messages array in your Vue template to display the received messages:

<template>
<div>
<h2>Messages from server:</h2>
<ul>
<li v-for="(message, index) in messages" :key="index">{{ message }}</li>
</ul>
</div>
</template>

The template renders a list of messages received from the server, providing a real-time user interface for your SSE events.

While this setup is rudimentary, it serves as a stepping stone for more intricate adaptations based on your project's specific needs. The beauty of this implementation lies in its simplicity and malleability; It can be tailored to handle different kinds of messages, add error handling, implement reconnect mechanisms, and more. The world of real-time updates is now at your fingertips.

--

--