phoenix
phoenix copied to clipboard
[Socket] send connect error to client and close
This is a draft solution for the discussion at https://elixirforum.com/t/websocket-connection-validation-with-phoenix-channels/48831
Previously if socket connect handler returns an error then websocket upgrade would be rejected. Browser websocket api doesn't support getting the status code on upgrade failure. This instead successfully upgrades to websocket then sends the error as the first message and immediately closes the socket. This is done instead of sending the error in the close frame payload because that payload is limited to 123 bytes which won't work well for errors provided by the application developer.
Close status code 3000 is chosen because RFC6455 states
Status codes in the range 3000-3999 are reserved for use by libraries, frameworks, and applications.
This change allows the application developer to return a custom error on socket connect to indicate for example an authentication/authorization error. The client can then implement custom behaviour based on the error.
See example client usage at https://github.com/BrendanBall/phoenix_socket_test/blob/master/assets/js/user_socket.js#L68.
If this change is acceptable then I can look at making this change in behaviour optional to prevent potential breaking changes with existing clients