Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
@fastify/websocket
Advanced tools
@fastify/websocket is a Fastify plugin that provides WebSocket support. It allows you to easily integrate WebSocket functionality into your Fastify applications, enabling real-time communication between the server and clients.
Basic WebSocket Server
This code sets up a basic WebSocket server using Fastify and the @fastify/websocket plugin. When a client connects to the /ws endpoint, the server listens for messages and responds with a confirmation message.
const fastify = require('fastify')();
const websocket = require('@fastify/websocket');
fastify.register(websocket);
fastify.get('/ws', { websocket: true }, (connection, req) => {
connection.socket.on('message', message => {
connection.socket.send(`Received: ${message}`);
});
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
Handling WebSocket Errors
This code demonstrates how to handle WebSocket errors. The server listens for error events on the WebSocket connection and logs the error to the console.
const fastify = require('fastify')();
const websocket = require('@fastify/websocket');
fastify.register(websocket);
fastify.get('/ws', { websocket: true }, (connection, req) => {
connection.socket.on('message', message => {
connection.socket.send(`Received: ${message}`);
});
connection.socket.on('error', error => {
console.error('WebSocket error:', error);
});
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
Broadcasting Messages to All Clients
This code shows how to broadcast messages to all connected WebSocket clients. When a client sends a message, the server broadcasts it to all other connected clients.
const fastify = require('fastify')();
const websocket = require('@fastify/websocket');
fastify.register(websocket);
let clients = [];
fastify.get('/ws', { websocket: true }, (connection, req) => {
clients.push(connection.socket);
connection.socket.on('message', message => {
clients.forEach(client => {
if (client !== connection.socket) {
client.send(`Broadcast: ${message}`);
}
});
});
connection.socket.on('close', () => {
clients = clients.filter(client => client !== connection.socket);
});
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
The 'ws' package is a popular WebSocket implementation for Node.js. It provides a simple and efficient way to create WebSocket servers and clients. Compared to @fastify/websocket, 'ws' is more low-level and does not integrate with Fastify out of the box, but it offers more control and flexibility for WebSocket handling.
Socket.IO is a library that enables real-time, bidirectional, and event-based communication between web clients and servers. It abstracts WebSocket communication and provides additional features like automatic reconnection, rooms, and namespaces. Compared to @fastify/websocket, Socket.IO offers more features and a higher-level API, but it may introduce more overhead.
WebSocket support for Fastify. Built upon ws@8.
npm i @fastify/websocket
# or
yarn add @fastify/websocket
If you're a TypeScript user, this package has its own TypeScript types built in, but you will also need to install the types for the ws
package:
npm i @types/ws -D
# or
yarn add -D @types/ws
After registering this plugin, you can choose on which routes the WS server will respond. This can be achieved by adding websocket: true
property to routeOptions
on a fastify's .get
route. In this case two arguments will be passed to the handler, the socket connection, and the fastify
request object:
'use strict'
const fastify = require('fastify')()
fastify.register(require('@fastify/websocket'))
fastify.register(async function (fastify) {
fastify.get('/', { websocket: true }, (socket /* WebSocket */, req /* FastifyRequest */) => {
socket.on('message', message => {
// message.toString() === 'hi from client'
socket.send('hi from server')
})
})
})
fastify.listen({ port: 3000 }, err => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
In this case, it will respond with a 404 error on every unregistered route, closing the incoming upgrade connection requests.
However, you can still define a wildcard route, that will be used as default handler:
'use strict'
const fastify = require('fastify')()
fastify.register(require('@fastify/websocket'), {
options: { maxPayload: 1048576 }
})
fastify.register(async function (fastify) {
fastify.get('/*', { websocket: true }, (socket /* WebSocket */, req /* FastifyRequest */) => {
socket.on('message', message => {
// message.toString() === 'hi from client'
socket.send('hi from wildcard route')
})
})
fastify.get('/', { websocket: true }, (socket /* WebSocket */, req /* FastifyRequest */) => {
socket.on('message', message => {
// message.toString() === 'hi from client'
socket.send('hi from server')
})
})
})
fastify.listen({ port: 3000 }, err => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
It is important that websocket route handlers attach event handlers synchronously during handler execution to avoid accidentally dropping messages. If you want to do any async work in your websocket handler, say to authenticate a user or load data from a datastore, ensure you attach any on('message')
handlers before you trigger this async work. Otherwise, messages might arrive whilst this async work is underway, and if there is no handler listening for this data it will be silently dropped.
Here is an example of how to attach message handlers synchronously while still accessing asynchronous resources. We store a promise for the async thing in a local variable, attach the message handler synchronously, and then make the message handler itself asynchronous to grab the async data and do some processing:
fastify.get('/*', { websocket: true }, (socket, request) => {
const sessionPromise = request.getSession() // example async session getter, called synchronously to return a promise
socket.on('message', async (message) => {
const session = await sessionPromise()
// do something with the message and session
})
})
Routes registered with @fastify/websocket
respect the Fastify plugin encapsulation contexts, and so will run any hooks that have been registered. This means the same route hooks you might use for authentication or error handling of plain old HTTP handlers will apply to websocket handlers as well.
fastify.addHook('preValidation', async (request, reply) => {
// check if the request is authenticated
if (!request.isAuthenticated()) {
await reply.code(401).send("not authenticated");
}
})
fastify.get('/', { websocket: true }, (socket, req) => {
// the connection will only be opened for authenticated incoming requests
socket.on('message', message => {
// ...
})
})
NB
This plugin uses the same router as the fastify
instance, this has a few implications to take into account:
fastify
request lifecycle, which means hooks, error handlers, and decorators all work the same way as other route handlers.this
in your handlers@fastify/websocket
, it needs to be registered before all routes in order to be able to intercept websocket connections to existing routes and close the connection on non-websocket routes.import Fastify from 'fastify'
import websocket from '@fastify/websocket'
const fastify = Fastify()
await fastify.register(websocket)
fastify.get('/', { websocket: true }, function wsHandler (socket, req) {
// bound to fastify server
this.myDecoration.someFunc()
socket.on('message', message => {
// message.toString() === 'hi from client'
socket.send('hi from server')
})
})
await fastify.listen({ port: 3000 })
If you need to handle both HTTP requests and incoming socket connections on the same route, you can still do it using the full declaration syntax, adding a wsHandler
property.
'use strict'
const fastify = require('fastify')()
function handle (socket, req) {
socket.on('message', (data) => socket.send(data)) // creates an echo server
}
fastify.register(require('@fastify/websocket'), {
handle,
options: { maxPayload: 1048576 }
})
fastify.register(async function () {
fastify.route({
method: 'GET',
url: '/hello',
handler: (req, reply) => {
// this will handle http requests
reply.send({ hello: 'world' })
},
wsHandler: (socket, req) => {
// this will handle websockets connections
socket.send('hello client')
socket.once('message', chunk => {
socket.close()
})
}
})
})
fastify.listen({ port: 3000 }, err => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
You can optionally provide a custom errorHandler
that will be used to handle any cleaning up of established websocket connections. The errorHandler
will be called if any errors are thrown by your websocket route handler after the connection has been established. Note that neither Fastify's onError
hook or functions registered with fastify.setErrorHandler
will be called for errors thrown during a websocket request handler.
Neither the errorHandler
passed to this plugin or fastify's onError
hook will be called for errors encountered during message processing for your connection. If you want to handle unexpected errors within your message
event handlers, you'll need to use your own try { } catch {}
statements and decide what to send back over the websocket.
const fastify = require('fastify')()
fastify.register(require('@fastify/websocket'), {
errorHandler: function (error, socket /* WebSocket */, req /* FastifyRequest */, reply /* FastifyReply */) {
// Do stuff
// destroy/close connection
socket.terminate()
},
options: {
maxPayload: 1048576, // we set the maximum allowed messages size to 1 MiB (1024 bytes * 1024 bytes)
verifyClient: function (info, next) {
if (info.req.headers['x-fastify-header'] !== 'fastify is awesome !') {
return next(false) // the connection is not allowed
}
next(true) // the connection is allowed
}
}
})
fastify.get('/', { websocket: true }, (socket /* WebSocket */, req /* FastifyRequest */) => {
socket.on('message', message => {
// message.toString() === 'hi from client'
socket.send('hi from server')
})
})
fastify.listen({ port: 3000 }, err => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
Note: Fastify's onError
and error handlers registered by setErrorHandler
will still be called for errors encountered before the websocket connection is established. This means errors thrown by onRequest
hooks, preValidation
handlers, and hooks registered by plugins will use the normal error handling mechanisms in Fastify. Once the websocket is established and your websocket route handler is called, fastify-websocket
's errorHandler
takes over.
By default, all ws connections are closed when the server closes. If you wish to modify this behaviour, you can pass your own preClose
function.
Note that preClose
is responsible for closing all connections and closing the websocket server.
const fastify = require('fastify')()
fastify.register(require('@fastify/websocket'), {
preClose: (done) => { // Note: can also use async style, without done-callback
const server = this.websocketServer
for (const socket of server.clients) {
socket.close(1001, 'WS server is going offline in custom manner, sending a code + message')
}
server.close(done)
}
})
Testing the ws handler can be quite tricky, luckily fastify-websocket
decorates fastify instance with injectWS
.
It allows to test easily a websocket endpoint.
The signature of injectWS is the following: ([path], [upgradeContext])
.
const Fastify = require('fastify')
const FastifyWebSocket = require('@fastify/websocket')
const ws = require('ws')
const fastify = Fastify()
await fastify.register(websocket)
fastify.get('/', { websocket: true }, (socket, req) => {
const stream = ws.createWebSocketStream(socket, { /* options */ })
stream.setEncoding('utf8')
stream.write('hello client')
stream.on('data', function (data) {
// Make sure to set up a data handler or read all the incoming
// data in another way, otherwise stream backpressure will cause
// the underlying WebSocket object to get paused.
})
})
await fastify.listen({ port: 3000 })
'use strict'
const Fastify = require('fastify')
const FastifyWebSocket = require('@fastify/websocket')
const App = Fastify()
App.register(FastifyWebSocket);
App.register(async function(fastify) {
fastify.addHook('preValidation', async (request, reply) => {
if (request.headers['api-key'] !== 'some-random-key') {
return reply.code(401).send()
}
})
fastify.get('/', { websocket: true }, (socket) => {
socket.on('message', message => {
socket.send('hi from server')
})
})
})
module.exports = App
'use strict'
const { test } = require('tap')
const Fastify = require('fastify')
const App = require('./app.js')
test('connect to /', async (t) => {
t.plan(1)
const fastify = Fastify()
fastify.register(App)
t.teardown(fastify.close.bind(fastify))
const ws = await fastify.injectWS('/', {headers: { "api-key" : "some-random-key" }})
let resolve;
const promise = new Promise(r => { resolve = r })
ws.on('message', (data) => {
resolve(data.toString());
})
ws.send('hi from client')
t.assert(await promise, 'hi from server')
// Remember to close the ws at the end
ws.terminate()
})
fastify.ready()
needs to be awaited to ensure that fastify has been decorated.@fastify/websocket
accept these options for ws
:
host
- The hostname where to bind the server.port
- The port where to bind the server.backlog
- The maximum length of the queue of pending connections.server
- A pre-created Node.js HTTP/S server.verifyClient
- A function which can be used to validate incoming connections.handleProtocols
- A function which can be used to handle the WebSocket subprotocols.clientTracking
- Specifies whether or not to track clients.perMessageDeflate
- Enable/disable permessage-deflate.maxPayload
- The maximum allowed message size in bytes.For more information, you can check ws
options documentation.
NB By default if you do not provide a server
option @fastify/websocket
will bind your websocket server instance to the scoped fastify
instance.
NB The path
option from ws
should not be provided since the routing is handled by fastify itself
NB The noServer
option from ws
should not be provided since the point of @fastify/websocket is to listen on the fastify server. If you want a custom server, you can use the server
option, and if you want more control, you can use the ws
library directly
ws does not allow you to set objectMode
or writableObjectMode
to true
This project is kindly sponsored by nearForm.
Licensed under MIT.
FAQs
basic websocket support for fastify
The npm package @fastify/websocket receives a total of 276,815 weekly downloads. As such, @fastify/websocket popularity was classified as popular.
We found that @fastify/websocket demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.