Fastify Server-Sent Events(SSE)

https://www.photopea.com/

What is the Server-Sent event?

Server-Sent event with Fastify.

Method 1:

$ mkdir sse-fastify
$ cd sse-fastify
$ npm init -y
$ npm install fastify fastify-cors
$ touch index-1.js
https://carbon.now.sh/
https://carbon.now.sh/
const headers = {
'Content-Type': 'text/event-stream',
Connection: 'keep-alive',
'Cache-Control': 'no-cache'
};
reply.raw.writeHead(200, headers);
reply.raw.write(JSON.stringify({ txt: new Date() }));
const clientId = req.id;const newClient = {
id: clientId,
response: reply
};
clients.push(newClient);
req.raw.on('close', () => {
console.log(`${clientId} Connection closed`);
clients = clients.filter((client) => client.id !== clientId);
});

Sample Output:

Method 2:

Initial Setup:

$ mkdir sse-fastify
$ cd sse-fastify
$ npm init -y
$ npm install fastify fastify-cors fastify-sse
$ touch index-2.js
https://carbon.now.sh/
const fastify = require('fastify');
const fastifySse = require('fastify-sse');
const app = fastify();
app.register(fastifySse);

Sample output:

https://carbon.now.sh/

--

--

--

Software developer / JavaScript / React / React Native / Firebase / Node.js / C Programming / Book Reader / Story Teller

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

React Redux tutorials for beginners-2

YouTube Video | Create Line Through Effect in JavaScript

Interacting With Smart Contracts Using Web3.js (Part II)

Mock Data for Angular 9 applications with JSON Server — Part 2(final)

ReactJS Tutorial for Beginners -2

JavaScript for Noobs Pt. 1: Variables and Data Types.

Create an Infinite Scroll with JavaScript

Simple 3D elements using ztext.js

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Edison Devadoss

Edison Devadoss

Software developer / JavaScript / React / React Native / Firebase / Node.js / C Programming / Book Reader / Story Teller

More from Medium

Announcing Ditsmod 2.0 beta (with RealWorld example)

Nested Pagination with Apollo Client 3 Type Policies

Using Node.js builtin modules with Vite

How to create authentication system with JWT using NestJS and Prisma.