Add CORS options to AWS websocket API Gateway

Viewed 1501

I have deployed an AWS websocket API Gateway, backed by lambda functions. I can successfully connect and exercise the websocket service from websocketking.com

When I try connecting from my client app (Angular, socket.io v3) I get the following error:

Access to XMLHttpRequest at 'https://sockets.example.com/socket.io/?EIO=4&transport=polling&t=NRSfmDM' from origin 'http://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How do I configure an AWS websocket API gateway to support CORS?

Thanks.

2 Answers

I initially thought it can be done in same way as for HTTP API - via CLI - https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html

However it seems there is no option to allow CORS for WebSocket protocol. I am seeing the message An error occurred (BadRequestException) when calling the UpdateApi operation: Cors is not supported for WEBSOCKET protocolType

Based on that I assume there is no support for the CORS at the moment for WebSocket protocol.

If it is an option for you, you can use custom domain for the API https://docs.aws.amazon.com/apigateway/latest/developerguide/websocket-api-custom-domain-names.html, so that both your web client and API will have same origin.

As answered by Milan, the AWS Websocket API Gateway protocol does not support CORS, and you would need to deploy your client-facing application to the same domain as your Websocket API.

I found that you will not need to specify CORS if you use WebSocket API on your client-side instead: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket on your client-side.

Basically, WebSocket protocol by default is not forcing your browser to check CORS policies: https://www.freecodecamp.org/news/how-to-secure-your-websocket-connections-d0be0996c556/

But since v3, socket.io explicitly requires you to enable them: https://socket.io/docs/v3/handling-cors/

Related