socketio / socket.io

Realtime application framework (Node.JS server)
https://socket.io
MIT License
61.2k stars 10.11k forks source link

Express Middleware Errors Do Not Stop Socket.IO Reconnections #5182

Open Nightmeru opened 2 months ago

Nightmeru commented 2 months ago

Describe the bug The documentation states that middleware errors should stop the client from reconnecting. However, this does not seem to be the case for middleware created using io.engine.use.

To Reproduce

Socket.IO server version: 4.7.5 Socket.IO client version: 4.7.5

Server

For example, let's create two middlewares that will trigger errors:

First:

io.use((socket, next) => {
  next(new Error('thou shall not pass and stop'))
})

Second:

io.engine.use((req, res, next) => {
  next(new Error('thou shall not pass'))
})

Client

Log the response as follows:

socket.on('connect_error', (err) => {
  console.log('websocket error:', err.message, socket.active)
})

Using the first middleware, the response is:

websocket error: thou shall not pass and stop false

Using the second middleware, however, the response is:

websocket error: xhr poll error true
websocket error: xhr poll error true
websocket error: xhr poll error true
...

Expected behavior I'm not sure if I missed something, but I believe that this type of middleware should, in fact, stop reconnections!

Platform:

darrachequesne commented 2 months ago

The middlewares at the Engine.IO level won't indeed stop the reconnections. Classic middlewares (io.use()) should work though. Could you please explain your use case?

Nightmeru commented 2 months ago

Thanks for the response! I have since switched to io.use(), and everything has been working pretty nicely.

I suppose my only issue now is that I have been (and still am) unable to find mentions of this behavior in the documentation. So, I'll explain the details.

I was implementing basic authentication with Passport and JWT and wanted to sign in the user after the page loads. Upon connection, the socket would then connect itself to user-specific rooms. On middleware failure, the socket would be disconnected until the user reloads the page or signs in manually.

As you might have guessed, this did not happen. I have skimmed through the docs a few times and, agh! I still can't find anything that describes this behavior.

As such, I would like to suggest describing this somewhere on: https://socket.io/docs/v4/middlewares/#compatibility-with-express-middleware or https://socket.io/docs/v4/server-api/#engineusemiddleware

Cheers!