fastify-websocket icon indicating copy to clipboard operation
fastify-websocket copied to clipboard

feat: add handleUpgradeRequest route option

Open infiton opened this issue 6 months ago • 1 comments

At gadget we make extensive use of @fastify/websocket. One use case is a websocket proxy that connects vite hmr clients in the browser to a developers serverless development environment. The vite client has a ping protocol with the following semantics:

  1. If the vite dev server listening then the hmr endpoint should upgrade the connection and immediately close
  2. If the vite dev server isn't listening yet the endpoint should reject the connection https://github.com/vitejs/vite/blob/main/packages/vite/src/node/server/ws.ts#L258-L263

We need a way to handle upgrade events in our proxy layer and not upgrade connections until we know that the upstream vite will also upgrade the connection. To do this I have introduced a route level option handleUpgradeRequest that allows for a route by route customization of how the upgrade event should be handled.

handleUpgradeRequest is a function that takes the incoming FastifyRequest, the source socket and the head buffer; to continue through to the normal wsHandler the use should return a promise that resolves to a connected websocket; to reject the connection the user can either throw an error (optionally with a statusCode) or write directly to/teardown the source socket

Checklist

infiton avatar Aug 06 '25 22:08 infiton

@mcollina any thoughts on this?

infiton avatar Aug 20 '25 15:08 infiton