@fastify/websocket
WebSocket support for Fastify, built on the `ws` library and integrated with Fastify routing.
@fastify/websocket
FastifyWebSocket 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
npm install @fastify/websocketUsage Example
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
Auto-load Fastify plugins from a directory — organize routes and plugins as files and let the framework discover them automatically.
@fastify/cookieFastifyPlugin for Fastify that adds support for reading and setting cookies, including signed cookies.
@fastify/corsFastifyCORS plugin for Fastify — configure cross-origin resource sharing with full support for preflight requests and dynamic origins.
@fastify/helmetFastifySecurity headers plugin for Fastify — sets HTTP headers that protect against common web vulnerabilities like XSS, clickjacking, and MIME sniffing.
@fastify/jwtFastifyJWT authentication plugin for Fastify — sign, verify, and decode tokens with a decorator-based API that integrates with Fastify's request lifecycle.