@fastify/websocket
WebSocket support for Fastify.
Built upon ws@8.
Install
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
Usage
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 }, (connection , req ) => {
connection.socket.on('message', message => {
connection.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 }, (connection , req ) => {
connection.socket.on('message', message => {
connection.socket.send('hi from wildcard route')
})
})
fastify.get('/', { websocket: true }, (connection , req ) => {
connection.socket.on('message', message => {
connection.socket.send('hi from server')
})
})
})
fastify.listen({ port: 3000 }, err => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
Attaching event handlers
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 }, (connection, request) => {
const sessionPromise = request.getSession()
connection.socket.on('message', async (message) => {
const session = await sessionPromise()
})
})
Using hooks
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) => {
if (!request.isAuthenticated()) {
await reply.code(401).send("not authenticated");
}
})
fastify.get('/', { websocket: true }, (connection, req) => {
connection.socket.on('message', message => {
})
})
NB
This plugin uses the same router as the fastify
instance, this has a few implications to take into account:
- Websocket route handlers follow the usual
fastify
request lifecycle, which means hooks, error handlers, and decorators all work the same way as other route handlers. - You can access the fastify server via
this
in your handlers - When using
@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 (connection, req) {
this.myDecoration.someFunc()
connection.socket.on('message', message => {
connection.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 (conn, req) {
conn.pipe(conn)
}
fastify.register(require('@fastify/websocket'), {
handle,
options: { maxPayload: 1048576 }
})
fastify.register(async function () {
fastify.route({
method: 'GET',
url: '/hello',
handler: (req, reply) => {
reply.send({ hello: 'world' })
},
wsHandler: (conn, req) => {
conn.setEncoding('utf8')
conn.write('hello client')
conn.once('data', chunk => {
conn.end()
})
}
})
})
fastify.listen({ port: 3000 }, err => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
Custom error handler:
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, conn , req , reply ) {
conn.destroy(error)
},
options: {
maxPayload: 1048576,
verifyClient: function (info, next) {
if (info.req.headers['x-fastify-header'] !== 'fastify is awesome !') {
return next(false)
}
next(true)
}
}
})
fastify.get('/', { websocket: true }, (connection , req ) => {
connection.socket.on('message', message => {
connection.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.
Custom preClose hook:
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) => {
const server = this.websocketServer
for (const connection of server.clients) {
connection.close(1001, 'WS server is going offline in custom manner, sending a code + message')
}
server.close(done)
}
})
Options
@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
You can also pass the following as connectionOptions
for createWebSocketStream.
allowHalfOpen
If set to false, then the stream will automatically end the writable side when the readable side ends. Default: true.readable
Sets whether the Duplex should be readable. Default: true.writable
Sets whether the Duplex should be writable. Default: true.readableObjectMode
Sets objectMode for readable side of the stream. Has no effect if objectMode is true. Default: false.readableHighWaterMark
Sets highWaterMark for the readable side of the stream.writableHighWaterMark
Sets highWaterMark for the writable side of the stream.
ws does not allow you to set objectMode
or writableObjectMode
to true
Acknowledgements
This project is kindly sponsored by nearForm.
License
Licensed under MIT.