How to Integrate WebSocket with Fastify.js


How to Integrate WebSocket with Fastify.js

Introduction

With the advancement of web technologies, the demand for real-time applications is increasing. Fastify.js is a Node.js-based, fast and low-resource web framework. With WebSocket integration in Fastify.js, you can create dynamic features like instant notifications, chat applications, and live data streams. This article explains step by step how WebSocket integration can be easily implemented with Fastify.js.

WebSocket Integration with Fastify.js

Installing Required Packages

We will use the popular fastify-websocket package for WebSocket support. First, add Fastify and its plugin to your project by running the following command in your terminal:

npm install fastify fastify-websocket

Basic Server Setup

You can review the example below to establish a simple WebSocket connection with Fastify.js. The server receives the message sent via WebSocket and sends it back to the client (echo).

const fastify = require('fastify')();
const websocket = require('fastify-websocket');

fastify.register(websocket);

fastify.get('/ws', { websocket: true }, (conn, req) => {
  conn.socket.on('message', message => {
    // Print the received message
    console.log('Received message:', message.toString());
    // Send the same message back to the client
    conn.socket.send('Echo: ' + message);
  });
});

fastify.listen({ port: 3000 }, err => {
  if (err) throw err;
  console.log('Fastify.js WebSocket server is running on port 3000');
});

Adding a WebSocket Client

You can use the following example to connect to the Fastify.js WebSocket server with a simple HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Fastify.js WebSocket Integration</title>
</head>
<body>
    <input type="text" id="mesaj" placeholder="Type your message">
    <button onclick="gonder()">Send</button>
    <div id="cevap"></div>
    <script>
        const soket = new WebSocket('ws://localhost:3000/ws');
        soket.onmessage = function(e) {
            document.getElementById('cevap').textContent = e.data;
        };
        function gonder() {
            const veri = document.getElementById('mesaj').value;
            soket.send(veri);
        }
    </script>
</body>
</html>

Conclusion

WebSocket integration with Fastify.js provides bidirectional, low-latency communication between server and client. Thanks to the speed and simple code structure this integration offers, you can choose Fastify.js for projects that require instant data streams. Setting up WebSocket connections with Fastify.js is fast and flexible. You can develop scalable and secure real-time applications on top of this basic structure.