@fastify/websocket

WebSocket support for Fastify, built on the `ws` library and integrated with Fastify routing.

@fastify/websocket

Fastify

WebSocket support for Fastify, built on the `ws` library and integrated with Fastify routing.

Fit

Bundle (gzip)

15.2 kB

50.6 kB raw

Install size includes transitive dependencies. Bundle size is gzipped browser payload.

Freshness

The Problem

Adding real-time WebSocket endpoints to a Fastify server usually means running a separate ws server alongside it, which complicates routing, lifecycle, and access to Fastify's hooks and decorators.

What It Does

@fastify/websocket lets you declare WebSocket routes directly in Fastify with the familiar route API, sharing the same server, hooks, and plugins. Each connection is handled through a standard ws socket.

Installation

bash
npm install @fastify/websocket

Usage Example

js
import Fastify from "fastify";
import websocket from "@fastify/websocket";

const app = Fastify();
await app.register(websocket);

app.get("/chat", { websocket: true }, (socket) => {
  socket.on("message", (message) => {
    socket.send(`echo: ${message}`);
  });
});

app.listen({ port: 3000 });

Related packages