Getting Started with Fastify WebSockets
Fastify offers impressive performance for Node.js web applications and is very developer-friendly. In addition to managing standard HTTP routes, Fastify smoothly works with WebSocket plugins, making it easy to build real-time features like chat systems, live dashboards, and collaborative tools.
Since Fastify's main focus is on core features, WebSocket support is added via the official @fastify/websocket plugin. This setup combines Fastify's speed and robust plugin system with dependable WebSocket communication.
This guide will walk you through building WebSocket features with Fastify step by step. You'll discover how to handle connections, broadcast messages, and manage clients effectively.
Prerequisites
To build WebSocket applications with Fastify, you'll want to make sure you have Node.js version 16 or newer installed on your system, along with npm. We’re also assuming you’re comfortable with Fastify routing and using JavaScript's async/await patterns.
Setting up your Fastify WebSocket project
WebSocket development becomes smoother with a tidy project structure, so let's set up a dedicated workspace. We'll kick things off by initializing a new Node.js project and installing all the essential dependencies to bring real-time features to life.
These commands help you set up a project directory, create a default package.json file, and activate ES module support for modern JavaScript syntax.
Feel free to install Fastify along with the WebSocket plugin and static file serving to get started.
Create your main server file with basic Fastify configuration:
This setup imports Fastify with logging enabled and registers the static file plugin to serve client-side files. The server configuration uses Fastify's recommended startup pattern with proper error handling.
Next, create a simple client interface for testing. Make a public directory and add an HTML file:
Add this basic WebSocket client to public/index.html:
This client creates a WebSocket connection to /websocket and provides basic message sending and display functionality. The interface includes keyboard shortcuts and auto-scrolling for better usability.
Update your server file to serve this HTML page:
Start your server to test the basic setup:
Visit http://localhost:3000 to see your demo interface:
The WebSocket connection will fail since we haven't implemented the server-side handler yet.
Creating your first WebSocket handler
Let's enhance your Fastify server by adding WebSocket functionality. The @fastify/websocket plugin offers an easy way to manage WebSocket connections while still handling your regular HTTP routes.
Simply register the WebSocket plugin and set up your very first connection handler—it's a smooth step forward in making your server more interactive and responsive:
Registering the plugin activates WebSocket support across your application. The route handler specifies { websocket: true } to denote WebSocket handling instead of HTTP responses. Fastify allows access to both the WebSocket connection and the original HTTP request for context.
The connection handler sends a welcome message, echoes incoming messages back to the sender, and logs connection events. This creates a simple echo server that confirms your WebSocket setup works correctly.
Restart your server and return to http://localhost:3000. Type a message and press Enter:
You should see your message echoed back in real time with an "Echo:" prefix.
Your first Fastify WebSocket server is working! Next, you'll learn how to handle connection errors robustly.
Adding connection error handling
WebSocket applications for production require reliable error handling to effectively address network problems, client disconnections, and unforeseen errors.
While your current setup handles simple cases, it needs more thorough error management. Let's improve it by implementing proper connection state control.
The new updates log client IP addresses for improved tracking and incorporate error event handling. The message handler now checks connection states to avoid sending messages to closed connections. The close event now also reports disconnection codes and reasons for debugging.
Restart your server and test at http://localhost:3000. When you close the browser tab or refresh the page, you will see detailed disconnection information in your terminal instead of silent failures.
This strong error handling is really important for applications where keeping a stable connection makes a big difference.
Broadcasting messages to multiple clients
Real WebSocket applications typically need to send messages to multiple clients simultaneously. Your current echo server only responds to individual senders. Let's build message broadcasting functionality to enable multi-client communication.
Create a simple connection manager to track and message multiple clients:
The connections Set tracks all active WebSocket connections, while the broadcast function sends messages to all clients except the sender. The function includes error handling to automatically remove broken connections.
When clients connect, they get a personalized welcome message, and the other clients are informed. Messages sent by any client are broadcasted to everyone, forming a simple chat system.
Restart your server and open multiple browser tabs to http://localhost:3000. You'll see connection notifications and user counts update in real-time:
Send a message from one tab and see it appear instantly in all the other tabs:
You've successfully built a real-time multi-client chat system with Fastify WebSockets.
Final thoughts
This article guided you through creating a real-time WebSocket app with Fastify's plugin system, starting from a basic echo server and advancing to a multi-client broadcaster with error handling.
For some great ideas on advanced features and ways to scale up, take a look at the @fastify/websocket docs and Fastify’s optimization guides. You might also want to think about adding authentication, message persistence, or horizontal scaling to make your setup even better.