Git Product home page Git Product logo

fastify-websocket's Introduction

fastify-websocket

CI NPM version Known Vulnerabilities js-standard-style

WebSocket support for Fastify. Built upon ws.

Install

npm install fastify-websocket --save

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.get('/', { websocket: true }, (connection /* SocketStream */, req /* FastifyRequest */) => {
  connection.socket.on('message', message => {
    // message === 'hi from client'
    connection.socket.send('hi from server')
  })
})

fastify.listen(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.get('/*', { websocket: true }, (connection /* SocketStream */, req /* FastifyRequest */) => {
  connection.socket.on('message', message => {
    // message === 'hi from client'
    connection.socket.send('hi from wildcard route')
  })
})

fastify.get('/', { websocket: true }, (connection /* SocketStream */, req /* FastifyRequest */) => {
  connection.socket.on('message', message => {
    // message === 'hi from client'
    connection.socket.send('hi from server')
  })
})

fastify.listen(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() // example async session getter, called synchronously to return a promise

  connection.socket.on('message', async (message) => {
    const session = await sessionPromise()
    // do somthing with the message and session
  })
})

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.
  • You can access the fastify server via this in your handlers
  • You can access the fastify request decorations via the req object 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.
'use strict'

const fastify = require('fastify')()

fastify.register(require('fastify-websocket'))

fastify.get('/', { websocket: true }, function wsHandler (connection, req) {
  // bound to fastify server
  this.myDecoration.someFunc()

  connection.socket.on('message', message => {
    // message === 'hi from client'
    connection.socket.send('hi from server')
  })
})

fastify.listen(3000, err => {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})

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) // creates an echo server
}

fastify.register(require('fastify-websocket'), {
  handle,
  options: { maxPayload: 1048576 }
})

fastify.route({
  method: 'GET',
  url: '/hello',
  handler: (req, reply) => {
    // this will handle http requests
    reply.send({ hello: 'world' })
  },
  wsHandler: (conn, req) => {
    // this will handle websockets connections
    conn.setEncoding('utf8')
    conn.write('hello client')

    conn.once('data', chunk => {
      conn.end()
    })
  }
})

fastify.listen(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:

'use strict'

const fastify = require('fastify')()

fastify.register(require('fastify-websocket'), {
  errorHandler: function (error, conn /* SocketStream */, req /* FastifyRequest */, reply /* FastifyReply */) {
    // Do stuff
    // destroy/close connection
    conn.destroy(error)
  },
  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 }, (connection /* SocketStream */, req /* FastifyRequest */) => {
  connection.socket.on('message', message => {
    // message === 'hi from client'
    connection.socket.send('hi from server')
  })
})

fastify.listen(3000, err => {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})

Options

fastify-websocket accept these options for ws :

  • objectMode - Send each chunk on its own, and do not try to pack them in a single websocket frame.
  • 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

Acknowledgements

This project is kindly sponsored by nearForm.

License

Licensed under MIT.

fastify-websocket's People

Contributors

airhorns avatar anthonyringoet avatar arnovsky avatar ayoubelk avatar birkenstab avatar blackglory avatar darkgl0w avatar delvedor avatar dependabot-preview[bot] avatar dependabot[bot] avatar einnjo avatar eomm avatar fdawgs avatar felixputera avatar fox1t avatar frando avatar frikille avatar greenkeeper[bot] avatar guskis avatar mcollina avatar mojo2600 avatar momennano avatar prinzhorn avatar salmanm avatar serayaeryn avatar shogunpanda avatar skellla avatar thegedge avatar wyozi avatar zekth avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.