Introduction
Server-Sent Events (SSE) is a powerful technology that enables servers to push real-time updates to web clients over HTTP. When combined with Angular on the client side and Node.js on the server side, SSE offers a seamless and efficient way to build dynamic, data-driven web applications. In this article, we'll explore how to implement SSE in an Angular application with a Node.js backend.
Understanding Server-Sent Events (SSE)
Server-Sent Events (SSE) is a standard mechanism for sending real-time updates from a server to a web client over HTTP. Unlike traditional HTTP requests, SSE establishes a persistent connection between the client and the server, allowing the server to send data to the client as events occur without the need for the client to repeatedly poll the server for updates.
Now, let's explore how to implement Server-Sent Events (SSE) using Angular + Node.js in a step-by-step manner.
Step 1. Setup Node.js Server
- Install Node.js: If you haven't already. You can download it from the Node.js official website.
- Create a new directory for your project and navigate into it using your terminal or command prompt.
- Initialize a new Node.js project by running the following command:
npm init -y - Install Express.js: a web application framework for Node.js, by running:
npm install express - Create a new file named `server.js
`in your project directory. This file will contain the code for your Node.js server.
Step 2. Write the server-side code for SSE
- Imports
import express from "express"; import http from "http"; import cors from "cors";Here, we import the necessary modules:
expressfor creating the server,httpfor creating an HTTP server instance, andcorsfor enabling Cross-Origin Resource Sharing. -
Server Setup
const app = express(); const server = http.createServer(app); app.use(cors());`express()`creates an Express application instance.
`http.createServer(app)`creates an HTTP server instance using the Express application.
`app.use(cors())`enables CORS to allow cross-origin requests. -
Route Definition
app.get("/curr-count", (req, res) => {}) - Setting Headers
res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive');`'Content-Type': 'text/event-stream'`specifies that the response will be an event stream.
`'Cache-Control'`: 'no-cache'disables caching.
`'Connection'`: 'keep-alive'keeps the connection open for further events. -
Data Streaming
let value = 0; setInterval(() => { res.write(`data: ${JSON.stringify({count: value++})}\n\n`); },2000)`value` is initialized to 0.
`setInterval()`is used to send events every 2 seconds.
`res.write()`writes data to the response stream. The data is formatted as an SSE event with a JSON payload containing the current count incremented each time.Note. Make sure that the server is sending events in the correct format. Each SSE event should start with data followed by the payload and end with.
-
Server Start
server.listen(3000, () => { console.log("server started at port 3000"); }) - Final Output
import express from "express"; import http from "http"; import cors from "cors"; const app = express(); const server = http.createServer(app); app.use(cors()); app.get("/curr-count", (req, res) => { res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); let value = 0; setInterval(() => { res.write(`data: ${JSON.stringify({count: value++})}\n\n`); },2000) }) server.listen(3000, () => { console.log("server started at port 3000"); })


Sujikumar TSPosted Apr 11, 2024, 6:25 AM
Good detailing!