AWS API Gateway WebSocket API: how to use it with React / NodeJS / native WebSocket?

Solution 1:

The reason why there is no response when you connect to the websocket is because you do not have the HTTP endpoint setup in your backend express app.

When you connect to the AWS API Gateway WebSocket API, WebSocket API takes action set by your $connect integration. In your current configuration, you have set the VPC Link integration with HTTP Method Any on the target url. Thus, for your backend endpoint to be called, you need to create a HTTP endpoint and set the address of the endpoint to "Endpoint URL."

For example, let's say you have the following route set up.

app.get('/connect', function(req, res) {
    res.send('success');
});

If you set the 'Endpoint URL' to '<BACKEND_URL>/connect', you will receive 'success' when you connect to the WebSocket.

In short, you don't need to be running the websocket server on your backend because WebSocket API takes care of it. Through the route integration, you just need to set up how different methods (which are provided by HTTP endpoints by your backend Node.js server) are invoked based on messages sent via WebSocket.

As a side note, I suggest one of the following options.

  1. If you need to run your own backend, do not use AWS API Gateway WebSocket API because there is no need to. You can use AWS ALB instead.
  2. If you don't have to run your own backend and if the features are not too complex, use AWS Lambda Integration with WebSocket API and take the real-time feature serverless. -- Edit (another suggestion based on the comment) --
  3. If you need to use API Gateway, you can set up the HTTP endpoints on your Node.js backend, and integrate it to the WebSocket API $connect integration. Then, the HTTP endpoint that you integrated will be invoked upon connection.