Skip to content

Commit c24adeb

Browse files
authored
fix/ws-error-handler - Handle WebSocket errors to avoid Node.js crashes (#228)
1 parent 6384aae commit c24adeb

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

index.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ function fastifyWebsocket (fastify, opts, next) {
6161
const connection = WebSocket.createWebSocketStream(socket, opts.connectionOptions)
6262
connection.socket = socket
6363

64+
connection.on('error', (error) => {
65+
fastify.log.error(error)
66+
})
67+
6468
connection.socket.on('newListener', event => {
6569
if (event === 'message') {
6670
connection.resume()

test/base.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -564,3 +564,25 @@ test('Should preserve the prefix in non-websocket routes', (t) => {
564564
t.error(err)
565565
})
566566
})
567+
568+
test('Should Handle WebSocket errors to avoid Node.js crashes', async t => {
569+
t.plan(1)
570+
571+
const fastify = Fastify()
572+
await fastify.register(fastifyWebsocket)
573+
574+
fastify.get('/', { websocket: true }, ({ socket }) => {
575+
socket.on('error', err => {
576+
t.equal(err.code, 'WS_ERR_UNEXPECTED_RSV_2_3')
577+
})
578+
})
579+
580+
await fastify.listen({ port: 0 })
581+
582+
const client = new WebSocket('ws://localhost:' + fastify.server.address().port)
583+
await once(client, 'open')
584+
585+
client._socket.write(Buffer.from([0xa2, 0x00]))
586+
587+
await fastify.close()
588+
})

0 commit comments

Comments
 (0)