Search code examples
angulartypescriptamazon-web-serviceswebsocketaws-api-gateway

Has anyone used the AWS WebSocket API Gateway and successfully connected with a typescript application (Angular/React etc)?


I have built an AWS WebSocket API gateway that functions correctly when using something like wscat or ws to connect. The issue is that these can't be used from the browser. It seems when using native JavaScript WebSocket the application successfully connects and then immediately disconnects with a status code of 1006 (Connection closed abnormally). No where on the browser nor on the CloudWatch logs does it give any indication as to why it is disconnecting abruptly. I need this connection to stay alive on the browser but both native JavaScript and the rxjs-websocket (which I think still uses this under the hood) disconnect immediately.

Some details around this, for authentication I followed this thread (using the Sec-WebSocket-Protocol header) and this seems to be successful for connecting. What I don't understand is why it immediately invokes my $disconnect route after connecting. The $connect route has a timeout of 29000 ms so it is not a timeout issue.

Is there a keepalive mechanism I need to be implementing? What are some alternatives on the client side that might be better suited for this? I have tried reconnecting until the connection stays open but this does not work either, have I perhaps missed a setting on the gateway itself?

Any help would be greatly appreciated.


Solution

  • For anyone who stumbles across this in future, if you use the Sec-WebSocket-Protocol header for auth (which is what Kubernetes does ) it won't work on Chrome unless your gateway responds with one of the same subprotocols. Can add your protocol to the lambda response of $connect https://docs.aws.amazon.com/apigateway/latest/developerguide/websocket-connect-route-subprotocol.html and then when connecting call it like so:

    const ws = new WebSocket(url, [subprotocol_to_respond_with, actual_token]);