fastify/fastify-websocket

Check if a request was websocket in `onRequest` hook

a-a-GiTHuB-a-a opened this issue ยท 8 comments

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

๐Ÿš€ Feature Proposal

I would like to see if a request was websocket in the onRequest hook, maybe through a req.ws boolean.

Motivation

I have a chat which uses the full declaration syntax with the websocket. However, I want my request to log differently if the request was a websocket.

Example

Maybe like this:

fastify.addHook("onRequest", async (req, res) => {
  if (req.ws) { //this is if it's a websocket
    req.log.info({req}, "websocket tryna connect");
  } else {
    req.log.info({req}, "regular old request");
  }
});

Are you hoping to do something differently with the request if it is a websocket upgrade request, or really just log something differently?

Actually both! See, when I open a websocket, it throws an INSANE amount of logs, almost one every .1 seconds!
If I fix this issue, I'm really just hoping to log it differently, but right now it's crucial as the websocket never connects and I can't find out why.
I have a link if there's some other way to debug this thing.

Eomm commented

Are you using a react app?
I face a similar issue when one component was connecting to the WebSocket at every component render.

No, it's not React.
Do you want the link?

I think it should be pretty easy to add something like this! Would you like to submit a PR? I would suggest adding an onRequest hook that checks if the request.raw[kWs] is present and sets a nice boolean property that you can then inspect in the route handler. I am not certain that'd work, it might have to be a preValidation hook, but there's definitely enough information to know if the request is upgraded yet or not.

Does it work with both the websocket: true and the wsHandler cases?

Not sure -- shouldn't be too hard to write a test for though!

Closed by #163